bayman
bayman

Reputation: 1719

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?

data = [
{
    "id": 1,
    "first_name": "John"
},
{   "id": 2,
    "first_name": "Mary"
},
{   "id": 3,
    "first_name": "John"
}
]

Upvotes: 0

Views: 137

Answers (3)

Mykola Zotko
Mykola Zotko

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

Mojtaba Kamyabi
Mojtaba Kamyabi

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

Fukiyel
Fukiyel

Reputation: 1166

You can use a set comprehension :

first_names = {d["first_name"] for d in data}

Upvotes: 3

Related Questions