daiyue
daiyue

Reputation: 7458

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.

Upvotes: 7

Views: 28435

Answers (7)

Subham
Subham

Reputation: 411

We can access only values as that's what OP wants and then sort it as follows :

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

arr = []
for key in sorted(dict1.values()):
    arr += key


print('{', ','.join(str(n) for n in arr), '}', sep='')

produces,

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

[Program finished]

as requested by OP.

Upvotes: 0

Akshay Kapoor
Akshay Kapoor

Reputation: 1

You can try this way:

keys_set= set()
for item in dict.values():
    keys_set.add(item)

Upvotes: 0

Adi219
Adi219

Reputation: 4814

Very simple, readable, self-explanatory solution without any imports:

arr = []
for key in dictionary:
    arr += list(dictionary[key])

answer = set(arr.sorted())

Upvotes: 2

Danula
Danula

Reputation: 3

A simpler way

set1 = set()
for i in dict.values():
    set1.update(i)
set1

Upvotes: 0

zipa
zipa

Reputation: 27899

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())

Upvotes: 12

omu_negru
omu_negru

Reputation: 4770

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)

Upvotes: 3

deceze
deceze

Reputation: 522626

A sequence reduction with the set union operator (|, "or") will do:

from functools import reduce
from operator import or_

d = {'key1': {8772, 9605},'key2': {10867, 10911, 10917},'key3': {11749,11750},'key4': {14721, 19755, 21281}}
s = reduce(or_, d.values())

It essentially does d['key1'] | d['key2'] | ....

Upvotes: 2

Related Questions