[英]Add new key to list of dictionaries with the values from a different dictionaries if matched with value of one key in each dictionary in a list
[英]Search for value in a key from list of dictionaries and return a different key value
繼續this 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):
for d in data:
if d['site'] == name:
return d['id']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.