列表中匹配元素的简明方法

时间:2015-05-26 22:53:41

标签: python

我有一个类似于

的列表
[{'name': 'red', 'test':4},... {'name': 'reded', 'test':44}]`

我有一个名字(例如:reded),我想找到上面列表中字典设置为name的{​​{1}}字典。这样做的简洁方法是什么?

我的尝试与

类似
reded

然后我做

x = [dict_elem for dict_elem in list_above if dict_elem['name']==reded]

如果名称匹配。这也可以用final_val = x[0] 来完成,但看起来似乎有一个简单的单线程。我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

你几乎就在那里。如果您使用生成器而不是列表理解,则可以将其传递给next,这将获取第一个项目。

try:
    x = next(dict_elem for dict_elem in list_above if dict_elem['name'] == reded)
except StopIteration:
    print "No match found"

或者

x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
    print "No match found"