TL;DR
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?
Details
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?