0
接下来的是stackoverflow question。 我有以下数据结构:从字典列表中搜索键中的值,并返回不同的键值
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
我要搜索所有的“现场”键的特定值,并返回该字典的“身份证”的价值。例如,搜索“超级用户”应该返回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
什么是这样做的最Python的方式?
'def find_id(data,name):return next((d ['id'] for d in data if d ['site'] == name),None)' – agf