⊗pyPmLpDV 153 of 208 menu

Dictionary values ​​via for in Python

To obtain dictionary values, you can access them by key.

Example

Let us have a dictionary dct:

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

Let's output all its values:

for key in dct: print(dct[key])

Result of code execution:

1 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:

for el in dct.values(): print(el)

Result of code execution:

1 2 3

Practical tasks

Given a dictionary:

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

Output its values ​​to the console:

1 2 3 4 5

Given a dictionary:

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

Find the sum of its values.

Given a dictionary:

tst = { '1': 'a', '2': 'b', '3': 'c', '4': 'd' }

Get the following string from its values:

'abcd'
byenru