访问没有嵌套循环的字典的嵌套级别

时间:2013-12-01 06:59:28

标签: python python-3.x dictionary python-3.3

我有一个字典,其中包含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中有什么东西可以让我这样做吗?

2 个答案:

答案 0 :(得分:3)

不确定它是否更好...我会坚持你的榜样,但它会变得更深,而不是像:

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]

答案 1 :(得分:1)

如果您不需要使用protocol,则可以itertools.chain.from_iterable使用map

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