Flatten nested dictionaries, compressing keys

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

    Here is a kind of a "functional", "one-liner" implementation. It is recursive, and based on a conditional expression and a dict comprehension.

    def flatten_dict(dd, separator='_', prefix=''):
        return { prefix + separator + k if prefix else k : v
                 for kk, vv in dd.items()
                 for k, v in flatten_dict(vv, separator, kk).items()
                 } if isinstance(dd, dict) else { prefix : dd }
    

    Test:

    In [2]: flatten_dict({'abc':123, 'hgf':{'gh':432, 'yu':433}, 'gfd':902, 'xzxzxz':{"432":{'0b0b0b':231}, "43234":1321}}, '.')
    Out[2]: 
    {'abc': 123,
     'gfd': 902,
     'hgf.gh': 432,
     'hgf.yu': 433,
     'xzxzxz.432.0b0b0b': 231,
     'xzxzxz.43234': 1321}
    

提交回复
热议问题