Merge nested dictionaries, by nested keys?

后端 未结 2 1669
终归单人心
终归单人心 2021-02-09 16:38

I have several dictionaries with different and common keys, plus different and common keys in the nested dictionary. Below is a simplified example, the actual dictionaries have

2条回答
  •  难免孤独
    2021-02-09 17:13

    from collections import defaultdict
    
    mydicts = [
       {1:{"Title":"Chrome","Author":"Google","URL":"http://"}},
       {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}},
       {2:{"Title":"Python","Version":"2.5"}},
    ]
    
    result = defaultdict(dict)
    
    for d in mydicts:
        for k, v in d.iteritems():
            result[k].update(v)
    
    print result
    

    defaultdict(, 
        {1: {'Version': '7.0.577.0', 'Title': 'Chrome', 
             'URL': 'http://', 'Author': 'Google'}, 
         2: {'Version': '2.5', 'Title': 'Python'}})
    

提交回复
热议问题