Merging Dictionaries in Python
Python provides the ability to merge two dictionaries. However, if we use the +
operator, we will get an error.
Let us have the following dictionaries:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = {
'e': 4,
'f': 5
}
Let's try to combine them using the operator +
:
print(dct1 + dct2) # will display an error
The correct solution would be to use the update
method. In its parameter, we specify the dictionary with which we will supplement the original:
dct1.update(dct2)
print(dct1) # {'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5}
Two dictionaries are given:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = {
'x': 4,
'y': 5,
'z': 6
}
Combine the dictionaries into one.
Two dictionaries are given:
dct1 = {
'3': 'c',
'4': 'd',
'5': 'e'
}
dct2 = {
'1': 'a',
'2': 'b'
}
Write the code to get the following result:
{'1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e'}
Two dictionaries are given:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = {
'x': 4,
'y': 5,
'z': 6
}
Merge dictionaries into one, then get a list of items in the new dictionary.
Three dictionaries are given:
dct1 = {
'a': 1,
'b': 2,
'c': 3
}
dct2 = {
'd': 4,
'e': 5,
'f': 6
}
dct3 = {
'j': 7,
'h': 8,
'i': 9
}
Combine the dictionaries into one.