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

442 Views Asked by At

I'm using Python 3.8. If I want to get a unique set of values for an array of dictionaries, I can do the below

>>> lis = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]
>>> s = set( val for dic in lis for val in dic.values())
>>> s
{1, 2, 3, 4}

However, how would I refine the above if I only wanted a unique set of values for the dictionary key "a"? In the above, the answer would be

{1, 3}

I'll assume that each dictionary in the array has the same set of keys.

2

There are 2 best solutions below

1
On BEST ANSWER

You could simply do:

lis = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]
# assuming the variable key points to what you want
key = 'a'
a_values = set(dictionary[key] for dictionary in lis)

I hope I've understood what you are looking for. Thanks.

0
On

You can do it like this:

lis = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]
search_key = 'a'
s = set(val for dic in lis for key, val in dic.items() if key == search_key)

print(s)

#OUTPUT: {1, 3}

Use the dic.items() instead of dic.values() and check where the key is a.

Another way to do it to simplify the things:

lis = [{"a": 1, "b": 2}, {"a": 3, "b": 4}]
search_key = 'a'
s = set(dic.get(search_key) for dic in lis)

print(s)