Flatten nested dictionaries, compressing keys

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

    Simple function to flatten nested dictionaries. For Python 3, replace .iteritems() with .items()

    def flatten_dict(init_dict):
        res_dict = {}
        if type(init_dict) is not dict:
            return res_dict
    
        for k, v in init_dict.iteritems():
            if type(v) == dict:
                res_dict.update(flatten_dict(v))
            else:
                res_dict[k] = v
    
        return res_dict
    

    The idea/requirement was: Get flat dictionaries with no keeping parent keys.

    Example of usage:

    dd = {'a': 3, 
          'b': {'c': 4, 'd': 5}, 
          'e': {'f': 
                     {'g': 1, 'h': 2}
               }, 
          'i': 9,
         }
    
    flatten_dict(dd)
    
    >> {'a': 3, 'c': 4, 'd': 5, 'g': 1, 'h': 2, 'i': 9}
    

    Keeping parent keys is simple as well.

提交回复
热议问题