Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert dict_values into a set

I have a dict that contains sets as values for each key, e.g.

{'key1': {8772, 9605},'key2': {10867, 10911, 10917},'key3': {11749,11750},'key4': {14721, 19755, 21281}}

Now I want to put each value, i.e. set of ints into a set, I am wondering what is the best way/most efficient way to do this.

{8772,9605,10867,10911,10917,11749,11750,14721,19755,21281}

I tried to retrieve the values from the dict using dict.values(), but that returns a dict_values object, making it a list, list(dict.values()) gave me a list of sets, set(list(exact_dups.values())) threw me errors,

TypeError: unhashable type: 'set'

UPDATE. forgot to mention the result set also need to maintain uniqueness, i.e. no duplicates.

like image 574
daiyue Avatar asked Dec 02 '22 12:12

daiyue


2 Answers

You can do it with set.union() and unpacked values:

set.union(*my_dict.values())

Or you can combine set.union() with reduce:

reduce(set.union, my_dict.values())
like image 171
zipa Avatar answered Jan 16 '23 02:01

zipa


Use a combination of reduce and set union:

from functools import reduce

result = reduce(lambda a, b: a.union(b), my_dict.values(), set())
print(result)
like image 33
omu_negru Avatar answered Jan 16 '23 04:01

omu_negru