Is there a Python dictionary method or simple expression that returns a value for the first key (from a list of possible keys) that exists in a dictionary?
Lets say I have a Python dictionary with a number of key-value pairs. The existence of any particular key not guaranteed.
d = {'A':1, 'B':2, 'D':4}
If I want to get a value for a given key, and return some other default value (e.g. None
) if that key doesn't exist, I simply do:
my_value = d.get('C', None) # Returns None
But what if I want to check a number of possible keys before defaulting to a final default value? One way would be:
my_value = d.get('C', d.get('E', d.get('B', None))) # Returns 2
but this gets rather convoluted as the number of alternate keys increases.
Is there a Python function that exists for this scenario? I imagine something like:
d.get_from_first_key_that_exists(('C', 'E', 'B'), None) # Should return 2
If such a method doesn't exist, is there a simple expression that is commonly used in such a scenario?
Using a plain old for loop, the flow control is clearest:
for k in 'CEB':
try:
v = d[k]
except KeyError:
pass
else:
break
else:
v = None
If you want to one-liner it, that's possible with a comprehension-like syntax:
v = next((d[k] for k in 'CEB' if k in d), None)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With