Unpack index, key, and value when enumerating over dictionary items

Question:

Let’s say I have the following code:

my_dict = {str(n*100): n for n in range(5)}
for index, key_value in enumerate(my_dict.items()):
    print(index, key_value[0], key_value[1])

Which would create a dictionary with 5 keys and then print (index, key, value) for each key-value pair in the dictionary.

Is there a more elegant way to unpack the dictionary items so that I could do something like:

for index, key, value in unpack_index_and_items(my_dict):
    print(index, key, value)

Preferably I’m looking for a one-line replacement for the unpack_index_and_items placeholder and not an actual function.

Asked By: Michael Leonard

||

Answers:

Sure, you can do this:

for index, (key, value) in enumerate(my_dict.items()):
    print index, key, value
Answered By: C_Z_

You are almost there. Just use this:

for index, (k, val) in enumerate(my_dict.items()):
    print(index, k, val)

Note the parenthesis around k, val. Without it you get ValueError: need more than 2 values to unpack. The reason is items() returns a (key, value) pair. Look here. Without parenthesis, the tuple returned by items() gets assigned to k, and there is nothing to assign to val, which is why you get the error need more than 2 values to unpack. However, with the parenthesis, the tuple returned by items() is assigned to the tuple (k, val).

I renamed the variables to k and val to distinguish between (key, value) pair returned by items() and the variable names in this example.


Edit: Read about tuple assignment here. Also PEP 3132: Extended Iterable Unpacking

Answered By: 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.