Convert a dictionary into a list of pairs in Python
This post will discuss how to convert a dictionary into a list of (key, value) pairs in Python.
For example, the dictionary {'A': 1, 'B': 2, 'C': 3} should be converted to [('A', 1), ('B', 2), ('C', 3)].
1. Using dict.items() function
The standard solution is to use the built-in function dict.items() to get a view of objects of (key, value) pairs present in the dictionary.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} pairs = d.items() print(pairs) # dict_items([('A', 1), ('B', 2), ('C', 3)]) |
Since the objects returned by dict.items() are just a dynamic view on the dictionary’s entries, you can use the list constructor to get a list, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} pairs = list(d.items()) print(pairs) # [('A', 1), ('B', 2), ('C', 3)] |
2. Using dict.keys() function
Alternatively, you can use the dict.keys() function to construct the list of dictionary’s (key, value) pairs. This can be easily achieved with List Comprehension, as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} pairs = [(k, d[k]) for k in d.keys()] print(pairs) # [('A', 1), ('B', 2), ('C', 3)] |
Another way to create the same list is pairs = [(k, v) for (k, v) in d.items()].
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} pairs = [(k, v) for (k, v) in d.items()] print(pairs) # [('A', 1), ('B', 2), ('C', 3)] |
3. Using zip() function
In the Python dictionary, keys and values are iterated over in insertion order. This allows creating (key, value) pairs using zip(), as shown below:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': d = {'A': 1, 'B': 2, 'C': 3} pairs = list(zip(d.keys(), d.values())) print(pairs) # [('A', 1), ('B', 2), ('C', 3)] |
That’s all about converting a dictionary into a list of pairs in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)