代码之家  ›  专栏  ›  技术社区  ›  user479870

按嵌套键合并嵌套词典?

  •  6
  • user479870  · 技术社区  · 15 年前

    我有几个不同的和共同的键字典,加上不同的和共同的键嵌套字典。下面是一个简化的例子,实际字典有数千个键。

    {1:{"Title":"Chrome","Author":"Google","URL":"http://"}}
    {1:{"Title":"Chrome","Author":"Google","Version":"7.0.577.0"}}
    {2:{"Title":"Python","Version":"2.5"}}
    

    我想合并成一本字典。

    {1:{"Title":"Chrome","Author":"Google","URL":"http://","Version":"7.0.577.0"},
     2:{"Title":"Python","Version":"2.5"}}
    

    我可以遍历这两个字典,比较键和 update 蟒蛇

    无需比较嵌套字典的值。

    2 回复  |  直到 15 年前
        1
  •  5
  •   nosklo    15 年前
    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(<type 'dict'>, 
        {1: {'Version': '7.0.577.0', 'Title': 'Chrome', 
             'URL': 'http://', 'Author': 'Google'}, 
         2: {'Version': '2.5', 'Title': 'Python'}})
    
        2
  •  2
  •   Thomas K    15 年前

    从您的示例来看,您可以执行以下操作:

    from collections import defaultdict
    mydict = defaultdict(dict)
    for indict in listofdicts:
        k, v = indict.popitem()
        mydict[k].update(v)