Dictionaries cannot have duplicate keys, therefore, the values of the third dictionary replace / overwrite the other values because they're evaluated from left to right, starting from dict1
, then dict2
and dict3
.
If you dictionaries would be, for example:
dict1= {9: 10, 8: 203, 7: 1456}
dict2 = {6: 34, 5: 2034, 4: 176}
dict3 = {3: 134, 2: 2340, 1: 126}
The output would be:
{9: 10, 8: 203, 7: 1456, 6: 34, 5: 2034, 4: 176, 3: 134, 2: 2340, 1: 126}
But since the keys of all the dictionaries are identical, they are just replaced by the new value.
For this case, I would use an array of tuples
(key-value pairs) to handle this better, avoiding overwriting:
dict1= {1: 10, 2: 203, 3: 1456}
dict2 = {1: 34, 2: 2034, 3: 176}
dict3 = {1: 134, 2: 2340, 3: 126}
finalDict = list(dict1.items()) + list(dict2.items()) + list(dict3.items())
print(finalDict)
Output:
[(1, 10), (2, 203), (3, 1456), (1, 34), (2, 2034), (3, 176), (1, 134), (2, 2340), (3, 126)]
Another alternative is to use a dictionary comprehension to form a list of values for each key, as follows:
dict1 = {1: 10, 2: 203, 3: 1456}
dict2 = {1: 34, 2: 2034, 3: 176}
dict3 = {1: 134, 2: 2340, 3: 126}
newDict = {key: [value, dict2[key], dict3[key]] for key, value in dict1.items()}
print(newDict)
Output:
{1: [10, 34, 134], 2: [203, 2034, 2340], 3: [1456, 176, 126]}