Access Nested Levels of a dict Without Nested Looping

dictionary, python, python-3.3, python-3.x

Solution

Not sure it's any nicer... I'd stick with what you've got for your example, but were it to become deeper, than something like:

myDict = {
    'p1': {1: [1, 2, 3], 2: [4, 5, 6]},
    'p2': {3: [7, 8, 9], 4: [0, 1, 2]}
}

from collections import Mapping

def go_go_gadget_go(mapping):
    for k, v in mapping.items():
        if isinstance(v, Mapping):
            for ok in go_go_gadget_go(v):
                yield [k] + ok
        else:
            yield [k] + [v]

for protocol, n, counts in go_go_gadget_go(myDict):
    print(protocol, n, counts)

# p2 3 [7, 8, 9]
# p2 4 [0, 1, 2]
# p1 1 [1, 2, 3]
# p1 2 [4, 5, 6]

Problem

I have a dictionary that contains simulation results of various protocols for various values of `n` ("protocols" and `n` are irrelevant to the problem I face). This dictionary is structured as follows: ``` myDict = {"protocol1" : {1:[some list of numbers], 2:[another list of numbers]}, "protocol2" : {1:[some list of numbers], 2:[another list of numbers]}, } ``` Now, in order to analyze the results, I would do something like this: ``` for protocol, stats in myDict.items(): for n, counts in stats.items(): # do stuff with protocol, n and counts ``` I wonder though, if there exists some set of built-ins that allow me to do this, without having to define a custom iterator: ``` for protocol, n, counts in magicFunc(myDict): # do stuff with protocol, n and counts ``` Is there something in `itertools` perhaps, that lets me do this?

Original source