devashish-patel
devashish-patel

Reputation: 723

Check multiple `keys` in Python dictionary

my_dict = {'a': 'Devashish'}

For example, if I do like: my_dict.get('A', None) #None

How to do like: my_dict.get('A', 'a', None) #'Devashish'

Basically, what I'm trying to achieve is check from 1st condition to n-1 and return the result when Key is matching otherwise return the last value.

Upvotes: 0

Views: 88

Answers (1)

timgeb
timgeb

Reputation: 78690

If I understand correctly, the following function should satisfy your specs.

>>> def get_first(dict_, keys,  default):
...     for k in keys:
...         try:
...             return dict_[k]
...         except KeyError:
...             pass
...     return default
... 
>>> get_first(d, [-1, 0, 3, 6], 'default')
4
>>> get_first(d, [-1, 0], 'default')
'default'

For fun, a recursive variant...

>>> def get_first(dict_, keys, default):
...     keys = iter(keys)
...     try:
...         k = next(keys)
...     except StopIteration:
...         return default
...     return dict_.get(k, get_first(dict_, keys, default))

>>> d = {1:2, 3:4, 5:6}
>>> get_first(d, [-1, 0, 3, 6], 'default')
4
>>> get_first(d, [-1, 0], 'default')
'default'

Alternatively, we can do it shorter via calling next on a genexp. Hashes the existing key twice, though.

>>> next((d[k] for k in [-1, 0, 3, 6] if k in d), 'default')
4
>>> next((d[k] for k in [-1, 0] if k in d), 'default')
'default'

Upvotes: 2

Related Questions