[英]Check multiple `keys` in Python dictionary
my_dict = {'a': 'Devashish'}
For example, if I do like: my_dict.get('A', None) #None
例如,如果我喜欢: my_dict.get('A', None) #None
How to do like: my_dict.get('A', 'a', None) #'Devashish'
怎么做: 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. 基本上,我想要实现的是从1st
条件检查到n-1
并在Key匹配时返回结果,否则返回最后一个值。
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. 另外,我们可以通过在genexp上调用next
来缩短它的执行时间。 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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.