合并嵌套字典,嵌套密钥? [英] Merge nested dictionaries, by nested keys?

查看:167
本文介绍了合并嵌套字典,嵌套密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字典具有不同的和常见的键,加上嵌套字典中的不同的和常用的键。以下是一个简化的例子,实际的字典有数千个键。

  {1:{Title:Chrome 作者:Google,URL:http://}} 
{1:{标题:Chrome,作者:Google,版本 .577.0}}
{2:{Title:Python,Version:2.5}}

我想合并成一个字典。

  {1:{标题:Chrome,作者:Google,URL:http://,版本:7.0.577.0},
2:{Title ,版本:2.5}}

我可以迭代这两个字典,比较键和更新嵌套字典,但可能有一种更有效率,或者是 pythonic 的方式来做到这一点。如果没有,哪个是最有效的?



嵌套字典的值不需要比较。

解决方案

  from collections import defaultdict 

mydicts = [
{1:{Title:Chrome,作者:Google,URL:http://}},
{1:{标题:Chrome,作者:Google,版本 .577.0}},
{2:{Title:Python,Version:2.5}},
]

result = defaultdict )

在mydicts中的d:
for k,v in d.iteritems():
result [k] .update(v)

打印结果






  defaultdict(< type'dict'> 
{1:{'Version':'7.0.577.0','Title':'Chrome',
'URL':'http: /','作者':'Google'},
2:{'版本':'2.5','标题':'Python'}})
pre>

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 thousands of keys.

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

Which I'd like to merge into a single dictionary.

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

I can iterate over both dictionaries, compare keys and update the nested dictionaries, but there is probably a more efficient, or pythonic, way to do this. If not, which is the most efficient?

Values of the nested dictionary need not be compared.

解决方案

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'}})

这篇关于合并嵌套字典,嵌套密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆