Dictionary values via for in Python
To obtain dictionary values, you can access them by key.
Example
Let us have a dictionary dct:
pythondct = {
'a': 1,
'b': 2,
'c': 3
}
Let's output all its values:
pythonfor key in dct:
print(dct[key])
Result of code execution:
python1
2
3
Example
You can also output dictionary values using the values method. It returns a special object that is iterated over in a loop:
pythonfor el in dct.values():
print(el)
Result of code execution:
python1
2
3
Practical tasks
Задание 1
Given a dictionary:
pythontst = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
Output its values to the console:
python1
2
3
4
5
Задание 2
Given a dictionary:
pythontst = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
Find the sum of its values.
Задание 3
Given a dictionary:
pythontst = {
'1': 'a',
'2': 'b',
'3': 'c',
'4': 'd'
}
Get the following string from its values:
python'abcd'