在其他的回答中,你被指如何解决给定的听写任务,最大深度为2。下面是一个程序,它可以让您循环遍历具有无限嵌套级别的dict的键值对(更通用的方法):def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield from recursive_items(value)
else:
yield (key, value)
a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
for key, value in recursive_items(a):
print(key, value)
印刷品1 2
3 4
5 6
如果您只对最深层的键值对感兴趣(当值不是dict时),则这一点是相关的。如果您还对值为dict的键值对感兴趣,请进行一个小编辑:def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield (key, value)
yield from recursive_items(value)
else:
yield (key, value)
a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
for key, value in recursive_items(a):
print(key, value)
印刷品a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6