Dictionary key value pair via for in Python

Using the for loop, you can also print the key-value pair of a dictionary.

Example

Let us have a dictionary dct:

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

Let's print all its elements. To do this, we specify the key and value in the print function:

pythonfor key in dct:
  print(key, dct[key])

Result of code execution:

python'a 1'
'b 2'
'c 3'

Example

You can also get the dictionary keys using the items method. The method returns a special iterable object that you can loop over:

pythonfor el in dct.items():
  print(el)

After executing the code, tuples consisting of key-value pairs will be output:

python('a', 1)
('b', 2)
('c', 3)

Practical tasks

Задание 1

Given a dictionary:

pythondct = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 4,
  'e': 5
}

Print the keys and values ​​of the elements to the console.

Задание 2

Create a dictionary containing the month ordinal number and its name. Print all key-value pairs of this dictionary.