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 int
s 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.
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())
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With