Get the value from the dictionary for the first key that exists

TL DR

Is there a Python dictionary method or a simple expression that returns a value for the first key (from a list of possible keys) that exists in the dictionary?

More details

Let's say that I have a Python dictionary with a series of key-value pairs. The existence of a particular key is not guaranteed.

d = {'A':1, 'B':2, 'D':4}

If I want to get a value for a given key and return another default value (for example None), if this key does not exist, I just do:

my_value = d.get('C', None) # Returns None

But what if I want to check a few possible keys before you default to default? One of the methods:

my_value = d.get('C', d.get('E', d.get('B', None))) # Returns 2

but this becomes rather confusing as the number of alternative keys increases.

Python ? - :

d.get_from_first_key_that_exists(('C', 'E', 'B'), None) # Should return 2

, , ?

+4
3

, :

for k in 'CEB':
    try:
        v = d[k]
    except KeyError:
        pass
    else:
        break
else:
    v = None

, , :

v = next((d[k] for k in 'CEB' if k in d), None)
+3

.

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

.

: :

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

( , )

+2

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)
+1
source

Source: https://habr.com/ru/post/1689935/


All Articles