将混合的嵌套字典转换为列表 [英] Convert a mixed nested dictionary into a list
本文介绍了将混合的嵌套字典转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的列表:
d1= {'Hiraki': {'Hiraki_2': ['KANG_751']}, 'LakeTaupo': {'LakeTaupo_4': ['KANG_708', 'KANG_785'], 'LakeTaupo_6': ['KANG_785'], 'LakeTaupo_2': ['KANG_751', 'KANG_785', 'KANG_785', 'KANG_785'], 'LakeTaupo_3': ['KANG_669', 'KANG_669', 'KANG_708', 'KANG_708', 'KANG_669']}}
我想将此嵌套列表转换为嵌套列表,例如:
I would like to convert this nested list into a nested list, like:
d2= ['Hiraki': ['Hiraki_2': ['KANG_751']], 'LakeTaupo': ['LakeTaupo_4': ['KANG_708', 'KANG_785'], 'LakeTaupo_6': ['KANG_785'], 'LakeTaupo_2': ['KANG_751', 'KANG_785', 'KANG_785', 'KANG_785'], 'LakeTaupo_3': ['KANG_669', 'KANG_669', 'KANG_708', 'KANG_708', 'KANG_669']]]
我下面的python代码无法将字典完全转换为列表:
My below python code does not convert the dictionary fully into a list:
list_key_value = [ [k,v] for k, v in d1.items() ]
请帮助我解决此问题.
推荐答案
请注意,您的d1
是字典,而不是列表,并且作为所需输出提供的嵌套列表"实际上不是有效的语法.字典和列表不是同一回事.
Note that your d1
is a dict, not a list, and that the "nested list" you give as your desired output is not actually valid syntax. A dictionary and a list are not the same thing.
也就是说,这是您要尝试进行的转换,以处理任意深度的嵌套字典的方式:
That said, here's how to do the conversion you're attempting in such a way as to handle arbitrarily deep nested dictionaries:
>>> def dict_to_list(d: dict) -> list:
... if isinstance(d, list):
... return d
... if isinstance(d, dict):
... return [[k, dict_to_list(v)] for k, v in d.items()]
... return [d]
...
>>> d1= {'Hiraki': {'Hiraki_2': ['KANG_751']}, 'LakeTaupo': {'LakeTaupo_4': ['KANG_708', 'KANG_785'], 'LakeTaupo_6': ['KANG_785'], 'LakeTaupo_2': ['KANG_751', 'KANG_785', 'KANG_785', 'KANG_785'], 'LakeTaupo_3': ['KANG_669', 'KANG_669', 'KANG_708', 'KANG_708', 'KANG_669']}}
>>> dict_to_list(d1)
[['Hiraki', [['Hiraki_2', ['KANG_751']]]], ['LakeTaupo', [['LakeTaupo_4', ['KANG_708', 'KANG_785']], ['LakeTaupo_6', ['KANG_785']], ['LakeTaupo_2', ['KANG_751', 'KANG_785', 'KANG_785', 'KANG_785']], ['LakeTaupo_3', ['KANG_669', 'KANG_669', 'KANG_708', 'KANG_708', 'KANG_669']]]]]
这篇关于将混合的嵌套字典转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文