访问dict的嵌套级别而不使用嵌套循环



我有一个字典,其中包含n的各种值的各种协议的模拟结果("协议"和n与我面临的问题无关)。这本词典的结构如下:

myDict = {"protocol1" : {1:[some list of numbers], 2:[another list of numbers]},
          "protocol2" : {1:[some list of numbers], 2:[another list of numbers]},
         }

现在,为了分析结果,我会做这样的事情:

for protocol, stats in myDict.items():
  for n, counts in stats.items():
    # do stuff with protocol, n and counts

不过,我想知道是否有一组内置程序允许我这样做,而不必定义自定义迭代器:

for protocol, n, counts in magicFunc(myDict):
  # do stuff with protocol, n and counts

也许itertools中有什么东西可以让我这么做吗?

不确定它是否更好。。。我会坚持你的例子,但如果它比更深入的话

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]

如果不需要使用protocol,可以将itertools.chain.from_iterablemap:一起使用

import itertools
for n, counts in itertools.chain.from_iterable(map(dict.items, myDict.values())):
    # do stuff with n and counts

最新更新