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?

XJ220
  • 31
  • 1
  • 1
  • 3

2 Answers2

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.

Mike McMahon
  • 7,096
  • 3
  • 30
  • 42
3

try using the following:

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