1

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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Dave
  • 15,639
  • 133
  • 442
  • 830

2 Answers2

2

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.

alani
  • 12,573
  • 2
  • 13
  • 23
Akashvshroff
  • 181
  • 1
  • 9
0

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)
Carlo Zanocco
  • 1,967
  • 4
  • 18
  • 31