Flatten nested dictionaries, compressing keys

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

    This is not restricted to dictionaries, but every mapping type that implements .items(). Further ist faster as it avoides an if condition. Nevertheless credits go to Imran:

    def flatten(d, parent_key=''):
        items = []
        for k, v in d.items():
            try:
                items.extend(flatten(v, '%s%s_' % (parent_key, k)).items())
            except AttributeError:
                items.append(('%s%s' % (parent_key, k), v))
        return dict(items)
    

提交回复
热议问题