我有一个字典,其中的键是字符串,其值是字典。深度定义并保持不变:3。当我需要遍历它时,我会执行以下操作:
for k1, v1 in d1.iteritems():
for k2, v2 in v1.iteritems():
for k3, v3 in v2.iteritems():
# Do something with k1, k2, k3 and v3
我想知道是否有更清晰的功能解决方案(我自己没有定义),这样我就可以这样做:
for k1, k2, k3, v3 in superfunction(d1):
# Do something...
提前致谢。
答案 0 :(得分:1)
如果您想要非常严格的代码,可以使用列表推导:
d={"A":{"B":{"C":"FOO"}}}
[(k1,k2,k3,v3) for k1,v1 in d.items() for k2,v2 in v.items() for k3,v3 in v1.items()]
但我不确定这比你正在做的要好得多。
答案 1 :(得分:1)
尝试实现执行它的迭代器。它比我想象的要复杂一点,但它有效,并且是任意级别的:
def superiter(d, l, cur = None):
if cur is None:
cur = [[]]
for k, v in d.iteritems():
if l == 1:
cur[0].extend((k, v))
yield cur[0]
cur[0] = cur[0][:-2]
else:
cur[0].append(k)
for x in superiter(v, l-1, cur):
yield x
cur[0] = cur[0][:-1]
In [112]: d1 = {1:{2:{3:4, 5:6}}, 10:{7:{8:9}}}
In [113]: for k1, k2, k3, v in superiter(d1, 3):
...: print k1, ' ', k2, ' ', k3, ' ', v
...:
1 2 3 4
1 2 5 6
10 7 8 9
In [114]: d2 = {1:{2:3, 4:5}, 6:{7:8}}
In [115]: for k1, k2, v in superiter(d2, 2):
...: print k1, ' ', k2, ' ', v
...:
1 2 3
1 4 5
6 7 8
并且它非常容易使其适用于深度不同的嵌套字典:
def superiter(d, cur = None):
if cur is None:
cur = [[]]
for k, v in d.iteritems():
if not isinstance(v, dict):
cur[0].extend((k, v))
yield cur[0]
cur[0] = cur[0][:-2]
else:
cur[0].append(k)
for x in superiter(v, cur):
yield x
cur[0] = cur[0][:-1]
In [120]: d1 = {1:{2:{3:4, 5:6}, 10:{7:{8:9}}}}
In [121]: list(superiter(d1))
Out[121]: [[1, 2, 3, 4], [1, 2, 5, 6], [1, 10, 7, 8, 9]]