Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict.get() or None scenario [duplicate]

I am attempting to access a dictionary's values based on a list of keys I have. If the key is not present, I default to None. However, I am running into trouble when the value is an empty string ''. Please see the code below for my examples

dict = {}
dict['key'] = ''
test = dict.get('key')
print(test)
>>

Above is as expected, and the empty string is printed. But now see what happens when I default the dict.get() function to None if the key is not present

dict = {}
dict['key'] = ''
test = dict.get('key') or None
print(test)
>> None

Why does this happen? In the second example the key is present so my intuition says '' should be printed. How does Python apply the 'or' clause of that line of code?

Below is the actual code I'm using to access my dictionary. Note that many keys in the dictionary have '' as the value, hence my problem.

# build values list
params = []
for col in cols:
    params.append(dict.get(col) or None)

Is there a best solution someone can offer? My current solution is as follows but I don't think it's the cleanest option

# build values list
params = []
for col in cols:
    if dict.get(col) is not None:
        params.append(dict.get(col))
    else:
        params.append(None)
like image 409
ProgrammingWithRandy Avatar asked May 11 '16 14:05

ProgrammingWithRandy


2 Answers

You don't need or None at all. dict.get returns None by default when it can't find the provided key in the dictionary.

It's a good idea to consult the documentation in these cases:

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

like image 161
DeepSpace Avatar answered Sep 28 '22 15:09

DeepSpace


You can simply use the second argument of get.

dict.get(col, None)

The second argument is the default for when it can't find the key. The or in that case takes the thing before the or if it is something, otherwise takes whatever is after the or.

like image 23
Matthias Schreiber Avatar answered Sep 28 '22 16:09

Matthias Schreiber