Flatten nested dictionaries, compressing keys

前端 未结 28 2244
遇见更好的自我
遇见更好的自我 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:45

    If you do not mind recursive functions, here is a solution. I have also taken the liberty to include an exclusion-parameter in case there are one or more values you wish to maintain.

    Code:

    def flatten_dict(dictionary, exclude = [], delimiter ='_'):
        flat_dict = dict()
        for key, value in dictionary.items():
            if isinstance(value, dict) and key not in exclude:
                flatten_value_dict = flatten_dict(value, exclude, delimiter)
                for k, v in flatten_value_dict.items():
                    flat_dict[f"{key}{delimiter}{k}"] = v
            else:
                flat_dict[key] = value
        return flat_dict
    

    Usage:

    d = {'a':1, 'b':[1, 2], 'c':3, 'd':{'a':4, 'b':{'a':7, 'b':8}, 'c':6}, 'e':{'a':1,'b':2}}
    flat_d = flatten_dict(dictionary=d, exclude=['e'], delimiter='.')
    print(flat_d)
    

    Output:

    {'a': 1, 'b': [1, 2], 'c': 3, 'd.a': 4, 'd.b.a': 7, 'd.b.b': 8, 'd.c': 6, 'e': {'a': 1, 'b': 2}}
    

提交回复
热议问题