Flatten nested dictionaries, compressing keys

前端 未结 28 2250
遇见更好的自我
遇见更好的自我 2020-11-22 01:16

Suppose you have a dictionary like:

{\'a\': 1,
 \'c\': {\'a\': 2,
       \'b\': {\'x\': 5,
             \'y\' : 10}},
 \'d\': [1, 2, 3]}

Ho

28条回答
  •  孤街浪徒
    2020-11-22 01:42

    If you want to flat nested dictionary and want all unique keys list then here is the solution:

    def flat_dict_return_unique_key(data, unique_keys=set()):
        if isinstance(data, dict):
            [unique_keys.add(i) for i in data.keys()]
            for each_v in data.values():
                if isinstance(each_v, dict):
                    flat_dict_return_unique_key(each_v, unique_keys)
        return list(set(unique_keys))
    

提交回复
热议问题