Getting Key-Value Pairs from Dictionary in Python

You can also get all the elements from a dictionary as a list of tuples containing key-value pairs. For this, the items method is used, which returns a special dict_items object.

Let's look at it in practice. Let's say we have the following dictionary:

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

Let's output all the elements from it:

pythonres = dct.items()
print(res) # dict_items([('a', 1), ('b', 2), ('c', 3)])

The dict_items object can be converted to a real list of tuples using the list function:

pythonres = list(dct.items())
print(res) # [('a', 1), ('b', 2), ('c', 3)]
Задание 1

Given a dictionary:

pythondct = {
  'x': 3,
  'y': 2,
  'z': 1
}

Get all its elements.

Задание 2

Given a dictionary:

pythondct = {
  'a': [2, 4],
  'b': [3, 5]
}

Get all its elements.

Задание 3

Given a dictionary:

pythondct = {
  1: 'x',
  2: 'y',
  3: 'z',
  4: 'w'
}

Get a list of tuples of its elements.

Задание 4

Given a dictionary:

pythondct = {
  'a': 12,
  'b': 34,
  'c': 56
}

Get all its elements in the following form:

python['a', 12, 'b', 34, 'c', 56]