August 25, 2018
Python concatenate and merge multiple dictionaries with same keys
Introduction
Imagine that we have two or more dictionaries and we want to combine them into a single dictionary. How can we do that in Python? How do we handle collision when keys are the same? Let us explore that…
Code snippets
Consider the following example…
1 2 3 |
# Note that key=3 is common engineering = {1:'Nathan', 2:'Nick', 3:'Jay'} marketing = {3:'Andre', 4:'Jerry', 5:'Ray'} |
- We can merge the two dictionaries into a third one while keeping the original ones intact. Here is how to do that…
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Combine both. The ** operator is used to # unpack the source dictionaries employees = {**engineering, **marketing} # If you print the original dictionaries # they should be the same as before print(engineering) print(marketing) # This is going to print: # {1: 'Nathan', 2: 'Nick', 3: 'Andre', 4: 'Jerry', 5: 'Ray'} # Note that key=3 is common so 'Jay' is going to be overwritten by 'Andre' print(employees) |
- Another way to merge the two dictionaries is to call the update function on one of the dictionaries. Take a look…
1 2 3 4 |
# This is going to print: # {1: 'Nathan', 2: 'Nick', 3: 'Andre', 4: 'Jerry', 5: 'Ray'} engineering.update(marketing) print(engineering) |
- Finally, we can do a manual update. Here is how…
1 2 3 4 5 6 |
# For each item in marketing add it to engineering for key, val in marketing.items(): engineering[key] = val # This should print: # {1: 'Nathan', 2: 'Nick', 3: 'Andre', 4: 'Jerry', 5: 'Ray'} print(engineering) |
I hope this post was useful. Please leave a comment if you have feedback