Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

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?

1 Answer

0 votes
by (36.8k points)

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}}

Do check out Data Science with Python course which helps you understand from scratch.

Browse Categories

...