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)