The reason your method is not working is because Python raises an error before your boolean expression is able to be evaluated. Instead of simply indexing the dictionary, you need to use .get()
instead. Rather than raising an error, .get()
returns None
which allows your expression to be evaluated correctly:
bar = foo.get('doesntexist') or foo.get('key1')
Note that if the value of the first key is 0
or any other value that evaluates to false, your method will fail. If this is fine with you than use the method above.
However, if you'd like not to have the behavior described above, you must test if the first value is None
. At this point however, it would be better to simply extract this logic to a separate function:
def get_key(d, test_key, default_key):
"""
Given a dictionary(d), return the value of test_key.
If test_key does not exists, return the default_key
instead.
"""
if d.get(test_key) is not None:
return d.get(test_key)
return d.get(default_key)
Which can be used like so:
foo = {'key1':'val1','key2':'val2'}
bar = get_key(foo, 'doesntexist', 'key1')