Python dictionaries which are used in data analytics frequently and by their nature are enclosed in {} and have key:value pairs, so the data in them can be retrieved easily.
There maybe a scenario where you need to merge two dictionaries, but how would you acheive this?
The good thing is that Python dictionaries are unordered and mutable, meaning that what makes them up can be changed.
Lets start off by creating two dictionaries
dict1 = {"A":"1", "B":"2", "C":"3"} dict2 = {"D":"4", "E":"5", "F":"6"} print("dictionary 1 is:", dict1) print("dictionary 2 is:", dict2) print(type(dict1)) print(type(dict2)) Its output is as follows: dictionary 1 is: {'A': '1', 'B': '2', 'C': '3'} dictionary 2 is: {'D': '4', 'E': '5', 'F': '6'} <class 'dict'> <class 'dict'>
So the objective is to get these two dictionaries into one, how is this achieved?
Approach 1 – Use PEP 448
This approach uses PEP 448 which allows * iterable unpacking operator and ** dictionary unpacking operators to be implemented.
As can be seen below , it is a quick and efficient way to quickly merge, without impacting the two dictionaries structure.
dict3 = {**dict1, **dict2} print(dict3) print(type(3)) With output: {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'} <class 'int'>
Approach 2 – Update when some values not required.
You maybe faced with a situation where you only want certain values from the second dictionary.
In the below there are common keys to both dictionares, namely “A” and “B”.
What the update is doing is it keeps all the values of dictionary 1, and adds in any key value pair that is not A or B.
This scenario could be encountered where dict1 is the master dictionary and always correct, and just needs new values added that do not exist already.
dict1 = {"A":"1", "B":"2", "C":"3"} dict2 = {"A":"2", "E":"5", "B":"6"} dict2.update((dict1)) print(dict2) print(type(dict2)) Resulting in: {'A': '1', 'E': '5', 'B': '2', 'C': '3'} <class 'dict'>
Approach 3 – Iterating over the dictionaries
In this scenario, there are a few things going on, that should be explained.
dict1.copy ===> This is done so that you have the original, as it maybe updated if there where duplicate keys.
The loop then just goes through dict2 key value pairs, and adds the key value pairs to dict3, which was originally dict1.
dict1 = {"A":"1", "B":"2", "C":"3"} dict2 = {"D":"4", "E":"5", "F":"6"} dict3 = dict1.copy() for key,value in dict2.items(): dict3[key] = value print(dict3) Which gives you: {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6'} <class 'dict'>
Summing it all up
In conclusion, depending on what way you would like to approach, we have outlined options.
Probably the most important thing that came out of this, is that dictionaries can be changed, as a result when applying some of the
techniques above, before proceeding be sure to check if you want to keep the original values.