How do I access the index of items inside an array that is inside a dictionary?

Viewed 502

I have a dictionary, wherein each key corresponds to a nested dictionary where the keys 1 and 2 each correspond to an array.

I need to iterate over the 2nd array for each key, and also keep track of the index that I am at inside the array inside the dict.

This is my code:

for key in mydict:
    for i, x in my_dict[key][2]:
         #other code here

This works for iterating over all the arrays:

for key in my_dict:
    for x in my_dict[key][2]:
        #code

But when I try the first block of code in order to keep track of index inside the array so that i can access the current object as well as the second object, I get:

ValueError: too many values to unpack (expected 2)

How do I fix this? If this is not the correct way to do what I need to, how do I keep track of the index i am at inside the array?

2 Answers

I think you meant to write:

for key in mydict:
    for i, x in enumerate(my_dict[key][2]):
         #other code here

I think it would be easier to iterate over the dict items rather than just the keys.

for k, v in my_dict.items():
    for k2, v2 in v.items():
        # code to act on v2, which is the nested list

Related