Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from dictionary for first key that exists [duplicate]

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?

like image 380
Andrew Guy Avatar asked Nov 28 '17 05:11

Andrew Guy


1 Answers

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)
like image 74
wim Avatar answered Nov 15 '22 21:11

wim