[英]How to get unique values from a specific key in a list of dictionaries?
給我一個包含字典的列表,我想從字典的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'}
如果你想有一個list
,而不是set
,你可以將其轉換為列表:
>>> list(set(i["first_name"] for i in data))
['John', 'Mary']
您可以將運算符itemgetter()
映射到列表中的字典:
from operator import itemgetter
iget = itemgetter('first_name')
set(map(iget, data))
# {'Mary', 'John'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.