13

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?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Andrew Guy
  • 9,310
  • 3
  • 28
  • 40

3 Answers3

6

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)
wim
  • 338,267
  • 99
  • 616
  • 750
  • Nice! The `for` loop is definitely more explicit, but I really like the comprehension example, especially with the use of `next`. – Andrew Guy Nov 28 '17 at 05:49
2

Nothing exists.

x = ["1", "3"]
d = {'1': 1, '2': 2, '3': 3}
d[[k for k in x if x in d][0]]

Just use a list comprehension.

Edit: Bonus Points:

all_matches = [d[k] for k in x if x in d]
all_matches[0]

if you'd like all possible keys (poor efficiency if you don't)

Mitchell Currie
  • 2,769
  • 3
  • 20
  • 26
1

You can do something like this

dict_keys=yourdict.keys()
expected_keys=['a','b','c']

result= list(set(dict_keys).intersection(set(expected_keys)))
if result:
    for i in expected_keys:
        if i in result:
            yourdict.get(i)
pushpendra chauhan
  • 2,205
  • 3
  • 20
  • 29