将字典附加到字典 [英] Append a dictionary to a dictionary

查看:108
本文介绍了将字典附加到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个现有的字典,我希望将其中一个追加"到另一个.我的意思是,另一个字典的键值应该做成第一个字典.例如:

I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:

orig = {
   'A': 1,
   'B': 2,
   'C': 3,
}

extra = {
   'D': 4,
   'E': 5,
}

dest = # Something here involving orig and extra

print dest
{
   'A': 1,
   'B': 2,
   'C': 3,
   'D': 4,
   'E': 5
}

我认为所有这一切都可以通过for循环来实现(也许吗?),但是是否有一些词典方法或其他任何模块可以为我节省工作呢?我正在使用的实际词典非常大...

I think this all can be achieved through a for loop (maybe?), but is there some method of dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big...

推荐答案

您可以

orig.update(extra)

,或者,如果您不想修改orig,请先进行复制:

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

请注意,如果extra和orig的键重叠,则最终值将取自extra.例如,

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

这篇关于将字典附加到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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