In Python, turning a dictionary into a nested or flattened list is one popular conversion you’ll find yourself carrying out.
Convert a Python Dictionary Into a List Using a for Loop
The for loop gives you more traction on your data while converting a Python dictionary into a list.
For instance, the following code converts a dictionary into a nested list:
The above code inserts each key (i) and value (myDictionary[i]) pair into individual lists and appends them into an empty list.
It’s the same as writing:
You can place each pair into a set or tuple too. All you need to do is replace the square braces ([]) around the key, value pair with curly braces ({}) or parenthesis (()) accordingly.
You can also achieve this using a for loop together with Python’s list comprehension feature:
Function to Convert a Python Dictionary Into a Flat List
While the above for loop options produce a nested list, you can destructure it further into a straight list if that’s what you want.
The following function does it:
The above function returns a flattened list, and the concept is simple. The loop appends each key and value pair to a list that the function returns when it’s finished.
Using Built-In One-Liner Functions
Both the map and zip functions allow for one-line Python solutions to this problem, with different results. They may be more suitable than the for loop, depending on your problem, and they’re certainly more convenient.
The zip function produces a nested list of tuples:
The map function, on the other hand, gives a list of lists:
Convert Between Python Lists and Dictionaries Either Way
These different ways to convert a dictionary into a list are pretty simple in Python. So, you can twist a dictionary into a list, but you can also do the opposite by converting a Python list into a dictionary.