Getting a ValueError: Not enough values to unpack for Python dictionary items unpacking


I have a dictionary with a single key-value pair where the key is a string and the value is a set of integers (i.e., dict[str, set[int]]).

I want to unpack the key and value by key, value = some_dict.items() but am getting a ValueError: not enough values to unpack (expected 2, got 1) error.

I suspected that this was because I wasn’t traversing the dictionary properly so I’ve tried the following which all lead to the same error:

>>> key, value = zip(some_dict.items())
>>> key, value = list(zip(some_dict.items()))

What works is:

for k, v in some_dict.items():
    key, value = k, v

How can I unpack the items without using a list?

Asked By: Sean



Try this approach:
If some_dict has multiple keys and values:
With the zip() method all keys and values will be unpacked

keys, values = zip(*some_dict.items())

print(keys) will print an array of keys. print(*keys, sep="n") will print individual key in a newline.

With the next() method you can unpack a key and a value at a time.

key, value = next(iter(some_dict.items()))
Answered By: Jamiu S.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.