Python - If value in dictionary then - python

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?

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.

try using the following:
if 'value' not in dictionary.values():
do something
else:
do something else.

Related

What's the shorter version for python dict checking key exist then get value?

if key in dict and dict[key]==value:
For the above, if statement, we first need to check the key that exists in dict then get the value. I'm curious do we have a shorter version or a better way for this?
Use dict.get(). It will return None if the key doesn't exist rather than raising an exception.
if dict.get(key) == value:
This will work as long as None isn't an actual value you might be comparing with, because you can't tell the difference between it being returned by default or from the dictionary. In that case, you need to provide some value that isn't a possible value. You could provide an empty object, since that creates a new list that can't be the same as one in the dictionary.
if dict.get(key, object()) == value:

searching "key" in a dictionary

Below you will see a snippet of a code where I created a dictionary in which words from a product review are stored. Now, I am writing a function that will return the number of occurrences of the word present in the dictionary. If it isn't present, it returns 0.
(This function will be used later for another purpose. As one of the member pointed, I could use dict.get() to extract the key. however, when I tried that, I got an attribute error:'SArray' object has no attribute 'get')
Can anyone point out any obvious mistake I might have made?
Thanks in advance.
Edit:
Here is the code:
word_list=turicreate.text_analytics.count_words(products['review'])
def selected_w_count(key):
if key in word_list:
return word_list[key]
else:
return 0
selected_w_count('wise')
output ->> 0
Snapshot of the code
You have a typo in selected_w_count(key) function, if key in world_list: should be if key in word_list:.
Based on your comment that the type of word_list is an array, you may want to use word_list[0].get('wise', 0) in place of the function call. This will get the dict from the array and get key 'wise' with a default value of 0.
It seems that your code returns a turicreate.SArray object but not a standard dict object, so the get function don't work.
I search for the document and find it at:
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.html
And maybe you can use the function turicreate.SArray.dict_trim_by_keys() to filter by the given keys and use turicreate.SArray.dict_values() to get the value, just like this:
def selected_w_count(key_word):
word_list.dict_trim_by_keys([key_word], exclude=False).dict_values() if word_list.dict_trim_by_keys([key_word], exclude=False) else 0
You can also just provide a list of key words, just change it like this:
def selected_w_count(keywords_list):
word_list.dict_trim_by_keys(keywords_list, exclude=False).dict_values() if word_list.dict_trim_by_keys(keywords_list, exclude=False) else 0
The documents of these functions are here:
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.dict_trim_by_keys.html
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.dict_values.html
Take care that the true result will also return A SArray of list type but not just a num.
Not sure whether it works, hope it can help you.

{ '__others__': None }

I came across a Python script that contained:
{'__others__': None}
This was assigned to a variable. I want to know what it does; can someone tell me, or direct me to somewhere where I can learn it myself?
That dictionary has no special meaning in Python. It is just a dictionary with a string key and None as the value.
Without more context it is impossible to tell why that codebase is using __others__ as a key, but as long as it remains just a key in a dictionary then it'll never amount to anything more than just another string key.
It is probably a special value chosen not collide with other strong keys to be stored.

Is there a more elegant way to write this in Python?

I want to append 'status' to the dict value indexed by 'update_fields' or add ['status'] as a value to kwargs indexed by 'update_fields' if that key isn't present.
kwargs.setdefault('update_fields', kwargs.get('update_fields', []).append('status'))
It's either this or about 3 lines of code, surely python can do better than this!
get and setdefault are essentially two methods of doing the same thing; putting them together is repeating yourself. The only difference between get and setdefault is that setdefault sets the value if the default doesn't exist. After that, they are identical semantically.
So this part:
kwargs.get('update_fields', [])
..is redundant. setdefault sets the default (and returns it, like get) if the dictionary doesn't have a value for that key yet, otherwise it just looks up the value associated with the key.
So all you need is:
kwargs.setdefault('update_fields', []).append('status')
You don't need the kwargs.get() bit, setdefault only sets the value if it's not already there, you can just write:
kwargs.setdefault('update_fields', []).append('status')

List of dictionaries: get() schould loop over list

I know it is easy to implement.
I want a dictionary like class, which takes a list of dictionaries in the constructor.
If you read from this dict by key, the dict-class should check the list of dictionaries and return the first value. If none contains this key KeyError should be thrown like a normal dict.
This dictionary container should be read only for my usage.
You seem to be describing collections.ChainMap, which will be in the next version of Python (3.3, expected to go final later this year). For current/earlier versions of Python, you can copy the implementation from the collections source code.
Not really answer to the question: what if you just define method that merge all dictionaries into one? Why make new class for it?
How to merge: How to merge two Python dictionaries in a single expression?
Varargs: Can a variable number of arguments be passed to a function?
You can easily implement this with this logic.
Iterate over all the dictionaries in the list.
For each dictionary, see if it has the required key by using key in value statement.
If value is found, return the value from the function.
If you have iterated over all dictionaries, and value is not found, Raise KeyError exception.

Categories

Resources