In my previous articles we discussed the following dictionary methods:
– get
– fromkeys
– copy
Feel free to read about them if you haven’t done so yet.
In this article we’ll be talking about another dictionary method, update.
Here’s the video version of this article:
The update method is used to merge dictionaries:
>>> scores = {"Brenda" : 16, "Luke" : 11}
>>> scores2 = {"Monica" : 12, "Jennifer" : 10, "Mike" : 8}
>>> scores.update(scores2)
>>> scores
{'Brenda': 16, 'Luke': 11, 'Monica': 12, 'Jennifer': 10, 'Mike': 8}
If we have the same keys in both dictionaries, they are overwritten. Here we have the key “Emma” in both:
>>> pets = {"Ron" : ["dog", "bunny"], "Emma" : ["cat", "hamster", "snake"]}
>>> pets2 = {"Steve" : ["cat"], "Emma" : ["skunk"]}
>>> pets.update(pets2)
>>> pets
{'Ron': ['dog', 'bunny'], 'Emma': ['skunk'], 'Steve': ['cat']}