【发布时间】:2011-08-16 16:29:50
【问题描述】:
继续stackoverflow question。 我有以下数据结构:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
我想在所有“站点”键中搜索特定值,并返回该字典的“id”值。例如,搜索“超级用户”应该返回 2:
>>> print find_id('Superuser')
2
当我尝试使用引用问题的解决方案时,我收到了一个错误:
>>> if any(d['site'] == 'Superuser' for d in data): print d['Superuser']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
>>> if any(d['site'] == 'Superuser' for d in data): print data['Superuser']
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
最pythonic的方式是什么?
【问题讨论】:
-
def find_id(data, name): return next((d['id'] for d in data if d['site'] == name), None)
标签: python list search dictionary key