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:

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

Let's output all its keys with indices:

pythonfor item in enumerate(dct):
  print(item)

After executing the code, tuples will be output, in which the index comes first, and then the key:

python(0, 'a')
(1, 'b')
(2, 'c')

Example

You can unpack the tuple into two variables:

pythonfor key, index in enumerate(dct):
  print(key, index)

Result of code execution:

python'a' 0
'b' 1
'c' 2

Practical tasks

Задание 1

Given a dictionary:

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

Print its indices and keys to the console as a tuple.

Задание 2

Given a dictionary:

pythontst = {
  '1': 11,
  '2': 12,
  '3': 13,
  '4': 14
}

Print its indices and keys to the console.

Задание 3

Given a dictionary:

pythontst = {
  'x': 10,
  'y': 20,
  'z': 30
}

Print its keys and indices to the console.