Reputation: 1719
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?
data = [
{
"id": 1,
"first_name": "John"
},
{ "id": 2,
"first_name": "Mary"
},
{ "id": 3,
"first_name": "John"
}
]
Upvotes: 0
Views: 137
Reputation: 17824
You can map the operator itemgetter()
to dictionaries in the list:
from operator import itemgetter
iget = itemgetter('first_name')
set(map(iget, data))
# {'Mary', 'John'}
Upvotes: 0
Reputation: 3600
>>> 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(i["first_name"] for i in data))
['John', 'Mary']
Upvotes: 3
Reputation: 1166
You can use a set comprehension :
first_names = {d["first_name"] for d in data}
Upvotes: 3