Convert A Mixed Nested Dictionary Into A List
I have a list like this: d1= {'Hiraki': {'Hiraki_2': ['KANG_751']}, 'LakeTaupo': {'LakeTaupo_4': ['KANG_708', 'KANG_785'], 'LakeTaupo_6': ['KANG_785'], 'LakeTaupo_2': ['KANG_751',
Solution 1:
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']]]]]
Post a Comment for "Convert A Mixed Nested Dictionary Into A List"