Dictionary index-element pairs in Python
To get the indices and elements of a dictionary as a tuple, use the enumerate function.
Example
Let us have a dictionary dct:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's output all its keys with indices:
for item in enumerate(dct):
print(item)
After executing the code, tuples will be output, in which the index comes first, and then the key:
(0, 'a')
(1, 'b')
(2, 'c')
Example
You can unpack the tuple into two variables:
for key, index in enumerate(dct):
print(key, index)
Result of code execution:
'a' 0
'b' 1
'c' 2
Practical tasks
Given a dictionary:
tst = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
}
Print its indices and keys to the console as a tuple.
Given a dictionary:
tst = {
'1': 11,
'2': 12,
'3': 13,
'4': 14
}
Print its indices and keys to the console.
Given a dictionary:
tst = {
'x': 10,
'y': 20,
'z': 30
}
Print its keys and indices to the console.