Min*_*dge 4 python dictionary iterator
我有一个 Python 字典,迭代中的层数越来越多。
我想遍历最后一层中存在的值。
假设这个字典:
d = {'a':{'a':2},'b':{'c':2},'x':{'a':2}}
#the intuitive solution is
for key1,val in d.items():
for key2,val2 in val.items():
#integer value in val2, HOORAY
Run Code Online (Sandbox Code Playgroud)
现在,如果我们添加一个层,循环将进行:
d = {'a':{'a':{'y':2}},'b':{'c':{'a':5}},'x':{'a':{'m':6}}}
#the intuitive solution is
for key1,val in d.items():
for key2,val2 in val.items():
for key3,val3 in val2.items():
#integer value in val3
Run Code Online (Sandbox Code Playgroud)
我寻找任意维度迭代的动态解决方案
如果有帮助,请考虑迭代中所有元素的已知和固定层数。
另外我想知道一个整数是如何在字典中映射的。
这最好使用递归解决:
def iter_leafs(d):
for key, val in d.items():
if isinstance(val, dict):
yield from iter_leafs(val)
else:
yield val
Run Code Online (Sandbox Code Playgroud)
用法示例:
>>> d = {'a':{'a':{'y':2}},'b':{'c':{'a':5}},'x':{'a':{'m':6}}}
>>> list(iter_leafs(d))
[6, 5, 2]
Run Code Online (Sandbox Code Playgroud)
如果您还想跟踪密钥:
def iter_leafs(d, keys=[]):
for key, val in d.items():
if isinstance(val, dict):
yield from iter_leafs(val, keys + [key])
else:
yield keys + [key], val
>>> list(iter_leafs(d))
[(['x', 'a', 'm'], 6), (['b', 'c', 'a'], 5), (['a', 'a', 'y'], 2)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1182 次 |
| 最近记录: |