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)
oroperator is printeddict.get('key').getalready returns None if it can't find the key.if dict.get(col) is not None: <use dict.get(col)> ; else: <use None which is the value of dict.get(col)>Really?for col in cols: params.append(dict.get(col)). Or you could simplify further to make the code a one-liner withparams = [dict.get(col) for col in cols], or ifcolsis huge and you really need that last ounce of performance,params = map(dict.get, cols)(wrap themapcall inlistif you're on Python 3 and needparamsto be a truelist, not a lazy generator that can be iterated exactly once and then discarded). Side-note: Don't name yourdict"dict" (or any other built-in name); name shadowing is bad.