Skip to content
Advertisement

Updating a python dictionary while adding to existing keys?

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement