2

Here's my code

    if "value" not in dictionary():
        do something
    else:
        do something else

I get the error 'TypeError: 'dict' object is not callable.

I've tried changing the first line to

    if dictionary["value"]:

But get a different error. Where am I going wrong here?

3

2 Answers 2

9

Assuming dictionary is in fact a dict() composed of key-values then it would be

if 'value' not in dictionary:
    ...etc

The error is essentially telling you that you are erroneously attempting to call a non-callable object as if it were a method/function.

If you are not particularly interested in whether or not a value exists you may use a method I am personally a fan of:

some_value = dictionary.get('value', 'valueIfNotPresent')
do_something(some_value)

The above allows you to provide a sentinel value (which is provided when the key does not exist). This can help with branch elimination (e.g. not having to if/else it, just allowing your code to act upon the sentinel) or at least reduce logic in checking for the existence of a key (unless the absence of a key is important).

Both are quite readable however and your mileage may vary.

EDIT:

@user1857805 is correct, if you are attempting to find out if a value is in a dictionary then the above (while still good and valid to know) is not enough. You will need to get the .values() as a list from the dictionary; however, as a dictionary may contain dictionaries you will need to recurse the dictionary to find all of the possibly stored values.

3
  • no worries, we've all been there a million times over. don't forget to mark the answers when appropriate :) Jun 15, 2015 at 22:04
  • @XJ220, if you are happy with an answer, you are supposed to use a 'green tick', not just an upvote...
    – garej
    Jun 15, 2015 at 22:10
  • Good use of the dictionary get method. Jun 15, 2015 at 22:17
3

try using the following:

if 'value' not in dictionary.values():
    do something
else:
    do something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.