Flatten nested dictionaries, compressing keys

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

    Code:

    test = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
    
    def parse_dict(init, lkey=''):
        ret = {}
        for rkey,val in init.items():
            key = lkey+rkey
            if isinstance(val, dict):
                ret.update(parse_dict(val, key+'_'))
            else:
                ret[key] = val
        return ret
    
    print(parse_dict(test,''))
    

    Results:

    $ python test.py
    {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
    

    I am using python3.2, update for your version of python.

提交回复
热议问题