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:

pythondct1 = {
  'a': 1,
  'b': 2,
  'c': 3
}

dct2 = {
  'e': 4,
  'f': 5
}

Let's try to combine them using the operator +:

pythonprint(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:

pythondct1.update(dct2)
print(dct1) # {'a': 1, 'b': 2, 'c': 3, 'e': 4, 'f': 5}
Задание 1

Two dictionaries are given:

pythondct1 = {
  'a': 1,
  'b': 2,
  'c': 3
}

dct2 = {
  'x': 4,
  'y': 5,
  'z': 6
}

Combine the dictionaries into one.

Задание 2

Two dictionaries are given:

pythondct1 = {
  '3': 'c',
  '4': 'd',
  '5': 'e'
}

dct2 = {
  '1': 'a',
  '2': 'b'
}

Write the code to get the following result:

python{'1': 'a', '2': 'b', '3': 'c', '4': 'd', '5': 'e'}
Задание 3

Two dictionaries are given:

pythondct1 = {
  '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.

Задание 4

Three dictionaries are given:

pythondct1 = {
  '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.