从字典中获取存在的第一个键的值 [英] Get value from dictionary for first key that exists

查看:65
本文介绍了从字典中获取存在的第一个键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有Python字典方法或简单表达式为字典中存在的第一个键(从可能的键列表中)返回一个值?

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?

让我们说我有一个带有许多键值对的Python字典.不能保证存在任何特定的密钥.

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}

如果我想获取给定键的值,并在不存在该键的情况下返回其他默认值(例如 None ),则只需执行以下操作:

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.

在这种情况下是否存在Python函数?我想像这样的东西:

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?

推荐答案

使用普通的for循环,流控制最清晰:

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)

这篇关于从字典中获取存在的第一个键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆