![]() |
In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dictionary to a List in PythonBelow, are the ways to Convert a Dictionary to a List in Python.
Convert a Dictionary to a List Using ‘items()’ MethodIn this example, the ‘items()’ method is used to retrieve key-value pairs from the dictionary, and then ‘list()’ is used to convert those pairs into a list of tuples. Python3
Output
<class 'dict'> Converted List: [('a', 1), ('b', 2), ('c', 3)] <class 'list'> Convert a Dictionary to a List Using List ComprehensionIn this example, a list comprehension is employed to iterate over the key-value pairs obtained from ‘items()’ and create a list of tuples. Python3
Output
<class 'dict'> Converted List: [('a', 1), ('b', 2), ('c', 3)] <class 'list'> Convert a Dictionary to a List Using zip() FunctionIn this example, below code uses the Python3
Output
<class 'dict'> Converted List: [('a', 1), ('b', 2), ('c', 3)] <class 'list'> Convert a Dictionary to a List Using * OperatorPython’s dictionary unpacking feature, using the `*` operator, allows for a concise conversion of a dictionary to a list. Python3
Output
<class 'dict'> Converted List: [('a', 1), ('b', 2), ('c', 3)] <class 'list'> ConclusionIn conclusion, converting a dictionary to a list in Python is a straightforward process with multiple approaches. Depending on your specific use case, you can choose between extracting keys, values, or key-value pairs. Whether you prefer the simplicity of the `list()` function, the elegance of list comprehensions, or the versatility of the `zip()` function, these methods provide the flexibility needed to adapt your data structures to various programming scenarios. |
Reffered: https://www.geeksforgeeks.org
Python Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |