在添加到现有密钥时更新一个蟒蛇字典? [英] Updating a python dictionary while adding to existing keys?

查看:125
本文介绍了在添加到现有密钥时更新一个蟒蛇字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最有效率和最有效的方式来更新字典,但如果存在现有的键,则保留旧值。例如...

  myDict1 = {'1':('3','2'),'3' ('2','1'),'2':('3','1')} 
myDict2 = {'4':('5','2'),'5' '2','4'),'2':('5','4')}

myDict1.update(myDict2)给了我以下....
$ b'b {'1':('3','2'),'3':('2','1'),'2':('5','4'),'5' ('2','4'),'4':('5','2')}



注意两个词典中的键2如何存在,并且用于具有值('3','1'),但现在它具有来自myDict2('5','4')中的键的值? / p>

有没有办法以有效的方式更新字典,因为键2最终具有值('3','1','5' '4')? #in no specific order



提前感谢

解决方案

最有效的方法是这样的:

  for k,v in myDict2.iteritems():
myDict1 [k] = myDict1.get(k,())+ v

但是有不幸的是,不幸的是,您想要做的事情相当于更新


I'm looking for the most efficient and pythonic (mainly efficient) way to update a dictionary but keep the old values if an existing key is present. For example...

myDict1 = {'1': ('3', '2'), '3': ('2', '1'), '2': ('3', '1')}
myDict2 = {'4': ('5', '2'), '5': ('2', '4'), '2': ('5', '4')}

myDict1.update(myDict2) gives me the following....

{'1': ('3', '2'), '3': ('2', '1'), '2': ('5', '4'), '5': ('2', '4'), '4': ('5', '2')}

notice how the key '2' exists in both dictionaries and used to have values ('3', '1') but now it has the values from it's key in myDict2 ('5', '4')?

Is there a way to update the dictionary in an efficient manner so as the key '2' ends up having values ('3', '1', '5', '4')? #in no particular order

Thanks in advance

解决方案

I think the most effective way to do it would be something like this:

for k, v in myDict2.iteritems():
    myDict1[k] = myDict1.get(k, ()) + v

But there isn't an update equivalent for what you're looking to do, unfortunately.

这篇关于在添加到现有密钥时更新一个蟒蛇字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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