Python 如果字典中存在另一个值,则访问字典列表中的一个值

Python Accessing a Value in a List of Dictionaries, if another Value in the Dictionary Exists

我的问题是对此的扩展:

Python Accessing Values in A List of Dictionaries

如果字典中存在另一个给定值,我只想 return 来自字典的值。

对于链接问题中给出的示例,如果字典中的 'Age' 值为“17”,则假设我只想 return 'Name' 值。

这应该输出

'Suzy' 

仅。

result = [d["Name"] for d in dicts if d.get("Age") == 17)]

当然这会select所有满足条件的名字。你可以把它放在一个函数中。

在以下情况下:

listname= [  
    {'Name': 'Albert' , 'Age': 16},
    {'Name': 'Suzy', 'Age': 17},
    {'Name': 'Johnny', 'Age': 13}
]

如果你想要 return 只有“年龄 == 17”时的人名,请使用:

for d in listname:
    if  d['Age'] == 17 :
        print (d['Name'])

在 for 中使用条件。

编辑 10/01/2022:将“list”更改为“listname”,因为列表已在 python.

中保留