Dave
Dave

Reputation: 19110

How do I find unique values for a specific key in a list of dictionaries?

I'm using Python 3.7. I have an array of dictionaries. All the dictionaries have the same keys, e.g.

a: 1
b: 2
c: 3

How do I find all the unique values for the key "a" for example? That is, if the array looked like

arr = [{"a": 1, "b": 5}, {"a": 1, "b": 3}, {"a": 2, "b": 1}]

I would want the result to be

(1, 2)

Upvotes: 5

Views: 6659

Answers (2)

Mark Snyder
Mark Snyder

Reputation: 1655

arr = [{"a": 1, "b": 5}, {"a": 1, "b": 3}, {"a": 2, "b": 1}]
unique_values = {d['a'] for d in arr}

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can use set() for this task:

arr = [{"a": 1, "b": 5}, {"a": 1, "b": 3}, {"a": 2, "b": 1}]

print( set(d['a'] for d in arr) )

Prints:

{1, 2}

Or in tuple form:

print( tuple(set(d['a'] for d in arr)) )

(1, 2)

Upvotes: 5

Related Questions