![](/img/trans.png)
[英]Accessing list of dictionaries in python and sort it using value (Nested dictionary)
[英]Python Accessing a Value in a List of Dictionaries, if another Value in the Dictionary Exists
我的問題是對此的擴展:
如果該字典中存在另一個給定值,我只想從字典中返回值。
對於鏈接問題中給出的示例,假設如果字典中的“年齡”值為“17”,我只想返回“姓名”值。
這應該是 output
'Suzy'
只要。
result = [d["Name"] for d in dicts if d.get("Age") == 17)]
當然,這將 select 所有滿足條件的納米。 你可以把它放在 function 中。
在以下情況下:
list= [
{'Name': 'Albert' , 'Age': 16},
{'Name': 'Suzy', 'Age': 17},
{'Name': 'Johnny', 'Age': 13}
]
如果您只想在“age == 17”時返回人名,請使用:
for d in list:
if d['Age'] == 17 :
print (d['Name'])
在 for 中使用條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.