python - 如何将 Python 多级字典转换为元组?
问题描述
我有一个多级字典,例如下面的示例,它需要以相反的顺序转换为元组,即最里面的元素应该首先用于创建元组。
{a: {b:c, d:{e:f, g:h, i:{j:['a','b']}}}}
输出应该是这样的:
[(j,['a','b']), (i,j), (g,h), (e,f), (d,e), (d,g), (d,i), (b,c), (a,b), (a,d)]
解决方案
你去了,这将产生你想要的(也经过测试):
def create_tuple(d):
def create_tuple_rec(d, arr):
for k in d:
if type(d[k]) is not dict:
arr.append((k, d[k]))
else:
for subk in d[k]:
arr.append((k, subk))
create_tuple_rec(d[k], arr)
return arr
return create_tuple_rec(d, [])
# Running this
d = {'a': {'b':'c', 'd':{'e':'f', 'g':'h', 'i':{'j':['a','b']}}}}
print str(create_tuple(d))
# Will print:
[('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'i'), ('d', 'e'), ('d', 'g'), ('i', 'j'), ('j', ['a', 'b']), ('e', 'f'), ('g', 'h')]
推荐阅读
- azure - 如何将 azure vm 网络接口连接到 azure 负载均衡器地址池?
- flutter - 在 Flutter 中导航时如何停止广播流?
- c++ - fstream 对象默认关联
- python - 散景箭头在情节中被切断
- spring - 注入来自依赖项但没有 @Bean 注释的 Spring bean
- java - 如何在已知方向上获得已知距离的点
- c - 如何更改缓冲区中的值 - 分配只读位置
- apache-spark - 使用 spark_sanitize_names 管理 pyspark 数据框中具有重复名称的多个列
- linux - Linux shell script on background, loop exit reading keyboard buffer
- python - lxml html ubnable to parse display block