TheEyesHaveIt
TheEyesHaveIt

Reputation: 1021

Python convert dict of lists to dict of sets?

I have:

myDict = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}

I want:

myDict = {'a': set([1,2,3]), 'b':set([4,5,6]), 'c':set([7,8,9])}

Is there a one-liner I can use to do this rather than looping through it and converting the type of the values?

Upvotes: 3

Views: 3882

Answers (4)

JoYSword
JoYSword

Reputation: 432

You can't do it without looping anyway, but you can have the looping done in one line, with the following code:

myDict = {k:set(v) for k, v in myDict.items()}

This is basically traversing each item in your dictionary and converting the lists to sets and combining the key(str):value(set) pairs to a new dictionary and assigning it back to myDict variable.

Upvotes: 1

mayurmadnani
mayurmadnani

Reputation: 199

You can use comprehension for it:

Basically, loop through the key-value pairs and create set out of each value for the corresponding key.

>>> myDict = {'a': [1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
>>> myDict = {k: set(v) for k, v in myDict.items()}
>>> myDict
{'a': {1, 2, 3}, 'b': {4, 5, 6}, 'c': {8, 9, 7}}

Upvotes: 1

vash_the_stampede
vash_the_stampede

Reputation: 4606

This can be done with map by mapping the values to type set

myDict = dict(map(lambda x: (x[0], set(x[1])), myDict.items()))

Or with either version of dictionary comprehension as well

myDict = {k: set(v) for k, v in myDict.items()}
myDict = {k: set(myDict[k]) for k in myDict}

Upvotes: 1

ForceBru
ForceBru

Reputation: 44838

You'll have to loop anyway:

{key: set(value) for key, value in yourData.items()}

If you're using Python 3.6+, you can also do this:

dict(zip(myDict.keys(), map(set, myDict.values())))

Upvotes: 8

Related Questions