[英]How to get unique values from a specific key in a list of dictionaries?
Give I have a list with dictionaries and I want to get all unique values from the key first_name from the dictionaries, how do I do that in python? 给我一个包含字典的列表,我想从字典的first_name键中获取所有唯一值,如何在python中做到这一点?
data = [
{
"id": 1,
"first_name": "John"
},
{ "id": 2,
"first_name": "Mary"
},
{ "id": 3,
"first_name": "John"
}
]
您可以使用set comprehension :
first_names = {d["first_name"] for d in data}
>>> set(i["first_name"] for i in data)
{'John', 'Mary'}
if you want a list
instead of set
you can convert it to list: 如果你想有一个
list
,而不是set
,你可以将其转换为列表:
>>> list(set(i["first_name"] for i in data))
['John', 'Mary']
You can map the operator itemgetter()
to dictionaries in the list: 您可以将运算符
itemgetter()
映射到列表中的字典:
from operator import itemgetter
iget = itemgetter('first_name')
set(map(iget, data))
# {'Mary', 'John'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.