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:
dct = {
'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:
for key in dct:
print(key, dct[key])
Result of code execution:
'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:
for el in dct.items():
print(el)
After executing the code, tuples consisting of key-value pairs will be output:
('a', 1)
('b', 2)
('c', 3)
Practical tasks
Given a dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
Print the keys and values of the elements to the console.
Create a dictionary containing the month ordinal number and its name. Print all key-value pairs of this dictionary.