Search code examples
pythonlistdictionarysetdictionary-comprehension

python dicts - convert the values on an existing dict from lists to sets


I have a dictionary that consists of strings for keys and lists for values. I keep running into errors when trying to convert the values into sets.

Here is an example:

>>> dict = {'hello': [0, 1, 2, 3], 'w': [0], 'c': [2, 3], 'dog': [4]}

The closest I've gotten is this, but then I run into 'too many values to unpack' errors when trying to merge that back into the dict via a comprehension:

>>> [set(v) for v in dict.values()]
[{0, 1, 2, 3}, {0}, {2, 3}, {4}]

I've tried to convert from tuples too, but still keep running into either 'unhashable type' or 'too many values to unpack' errors depending on the approach. Any tips?


Solution

  • Convert to dict using dict comprehension.

    dict = {'hello': [0, 1, 2, 3], 'w': [0], 'c': [2, 3], 'dog': [4]}
    
    {k : set(v) for k, v in dict.items()}
    
    # Output
    # {'hello': {0, 1, 2, 3}, 'w': {0}, 'c': {2, 3}, 'dog': {4}}