将字典附加到字典?

编程入门 行业动态 更新时间:2024-10-19 09:39:09
本文介绍了将字典附加到字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有两个现有的字典,我希望将其中一个添加到另一个。我的意思是,其他词典的关键,价值应该是第一个字典。例如:

orig = {'A':1,'B' 'C':3,} extra = {'D':4,'E':5, dest =#这里涉及到原始和额外的 打印dest {'A':1,'B' :2,'C':3,'D':4,'E':5 } pre>

我认为这一切可以通过循环(也许?)中的来实现,但是有一些方法的字典或任何其他模块,为我保存这份工作?我使用的实际字典真的很大...

解决方案

你可以做

orig.update(extra)

或者,如果您不希望修改 orig ,请先复制一份:

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

请注意,如果extra和orig具有重叠的键,则最终值将从额外的值中获取。例如,

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

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 }

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...

解决方案

You can do

orig.update(extra)

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

dest = dict(orig) # or orig.copy() dest.update(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}

更多推荐

将字典附加到字典?

本文发布于:2023-11-26 20:51:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!