Python 无嵌套循环访问dict的嵌套级别

Python 无嵌套循环访问dict的嵌套级别,python,python-3.x,dictionary,python-3.3,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

我有一本字典,其中包含了各种协议的模拟结果,其值为
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]

但它仍然隐式循环两次,对吗?当然,它可能更快,但里面有一个隐含的外观。@GamesBrainiac,无论如何,循环是不可避免的。@ChadMiller,在我发布答案后,问题发生了变化。我确实需要使用
协议
。我编辑了我的帖子来反映这一点。很抱歉搞混了@GamesBrainiac:隐式双循环在这一点上不太重要。我希望能够展开所有层次的嵌套,而不需要太多的努力。因此,对
map(dict.items,myDict.values())
的调用更令人担忧,因为这不容易扩展到更高的级别nesting@inspectorG4dget我也在想,你能期望的最快的速度就是列表理解。我正在做一些事情,让我们看看它是否有效。但问题是,如果没有双环,这将是很困难的。就目前而言,我会坚持你所拥有的。如果你使用第二个dict,而不是列表中有更多dict的列表中有更多dict,那么实际上,你会使用dict压扁器并从中获得收益。否则,您当前问题的任何解决方案都将变得更加模糊和不值得…
您将使用dict扁平化器。这样的东西存在吗(非常感兴趣),还是我必须自己写(不太感兴趣)?快速举了一个例子来说明我的意思。。。。如果你得到更深层的嵌套,它可能有一些价值——否则——坚持你得到的东西……为什么不
[k,v]
而不是
[k]+[v]
?@falsetru这会比复制粘贴和将
v
更改为列表更容易,不是吗:p
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]