Flatten nested dictionaries, compressing keys

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

    The answers above work really well. Just thought I'd add the unflatten function that I wrote:

    def unflatten(d):
        ud = {}
        for k, v in d.items():
            context = ud
            for sub_key in k.split('_')[:-1]:
                if sub_key not in context:
                    context[sub_key] = {}
                context = context[sub_key]
            context[k.split('_')[-1]] = v
        return ud
    

    Note: This doesn't account for '_' already present in keys, much like the flatten counterparts.

提交回复
热议问题