Dictionary keys via for in Python
When iterating over a dictionary with the for
loop, its keys are always printed by default.
Example
Let us have a dictionary dct
:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's run it in a loop:
for key in dct:
print(key)
As a result of executing the code, all keys will be displayed:
'a'
'b'
'c'
Example
You can also get the dictionary keys using the keys
method. The method returns a special object that can be iterated over in a loop:
for key in dct.keys():
print(key)
Result of code execution:
'a'
'b'
'c'
Practical tasks
Given a dictionary:
tst = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
Output its keys to the console:
'a'
'b'
'c'
'd'
'e'
Given a dictionary:
tst = {
2: 'a',
4: 'b',
6: 'c',
8: 'd'
}
Print its keys to the console, except 8
.
Given a dictionary:
tst = {
'1': 'a',
'2': 'b',
'3': 'c',
'4': 'd'
}
Obtain the following tuple from its keys:
('2', '3', '4')