Ratnanil
Ratnanil

Reputation: 1752

Loop over nested dictionary with duplicate indicies

I'm trying to set up a nested dictionary with indicies and loop a certain command over this nested dictionary.

dictionary = {"item 1":{"subitem 1":"one of one","subitem 2":"two of one"},"item 2":{"subitem 1":"one of two", "subitem 2":"two of two"}}

The output of the first "round" (or first loop) should be:

some.command{input:one of one, output: two of one}

The output of the second "round":

some.command{input:one of two, output:two of two}

and so on. I really want to work with indicies, simply looping through all the entries on the second level dictionary won't do (since there are entries the command has to ignore). The loop should look something like this:

for x in dictionary.itervalues():
    for y in x.itervalues():
        some.command(input: y["subitem 1], output: y["subitem 2"])

This somehow doesn't work, since I cant get access to selected values via the index. If I replace "some.command" with "print y["subitem 1"] I get the error "TypeError: string indices must be integers, not str".

What am I doing wrong? Am I setting up my dictionary up the wrong way or my loop command or both?

Upvotes: 1

Views: 171

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

x is already your nested dictionary; you don't need your inner loop. Rather than use x (a rather meaningless name), I used nested_dict to clarify what your loop is iterating over:

for nested_dict in dictionary.itervalues():
    some.command(input=nested_dict["subitem 1"], output=nested_dict["subitem 2"])

Your inner loop then, was looping over the values of that those nested dictionaries; y was bound to "one of one", then "two of one", etc. Trying to use y['some string'] was trying to apply indexing to those strings.

Also, nowhere in these for loops is Python using indices. Python for loops iterate directly over the items. You are telling Python to loop over dictionary.itervalues(), so each nested_dict is bound to each of the values of dictionary. No indices are being used.

Upvotes: 2

Related Questions