从字典列表中搜索键中的值并返回不同的键值
继续此 stackoverflow 问题。 我有以下数据结构:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
我想在所有“site”键中搜索特定值,并返回该字典的“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 方法是什么?
Continued from this stackoverflow question.
I have the following data structure:
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
I want to search all 'site' keys for a specific value, and return that dictionary's 'id' value. For example, searching 'Superuser' should return 2:
>>> print find_id('Superuser')
2
When I tried using the referenced question's solution, I received an error:
>>> 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
What's the most pythonic way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里没有技巧。只要这样做:
No tricks here. Just do: