Flatten nested dictionaries, compressing keys

前端 未结 28 2941
遇见更好的自我
遇见更好的自我 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 similar to both imran's and ralu's answer. It does not use a generator, but instead employs recursion with a closure:

    def flatten_dict(d, separator='_'):
      final = {}
      def _flatten_dict(obj, parent_keys=[]):
        for k, v in obj.iteritems():
          if isinstance(v, dict):
            _flatten_dict(v, parent_keys + [k])
          else:
            key = separator.join(parent_keys + [k])
            final[key] = v
      _flatten_dict(d)
      return final
    
    >>> print flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]})
    {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
    

提交回复
热议问题