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:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's output all the elements from it:
res = 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:
res = list(dct.items())
print(res) # [('a', 1), ('b', 2), ('c', 3)]
Given a dictionary:
dct = {
'x': 3,
'y': 2,
'z': 1
}
Get all its elements.
Given a dictionary:
dct = {
'a': [2, 4],
'b': [3, 5]
}
Get all its elements.
Given a dictionary:
dct = {
1: 'x',
2: 'y',
3: 'z',
4: 'w'
}
Get a list of tuples of its elements.
Given a dictionary:
dct = {
'a': 12,
'b': 34,
'c': 56
}
Get all its elements in the following form:
['a', 12, 'b', 34, 'c', 56]