How to convert Python dictionary to list

Data manipulation happens a lot in programming, depending on the problem you intend to solve. You may often find yourself converting one data structure to another. Some types are so similar that converting between them is a straightforward process.
In Python, turning a dictionary into a nested or flattened list is a popular conversion you’ll find yourself performing.
Convert a Python dictionary to a list using a for loop
The for loop gives you more traction on your data while converting a Python dictionary to a list.
For example, the following code converts a dictionary to a nested list:
myDictionary = {"A": "Python", "B": "JavaScript", "C": "Node"}
convertedList = []for i in myDictionary:
convertedList.append([i, myDictionary[i]])
print(convertedList)
The above code inserts each key (I) and the value (My dictionary[i]) pair in individual lists and appends them to an empty list.
This is the same as writing:
for key, value in myDictionary.items():
convertedList.append([key, value])
You can also place each pair in a set or a tuple. You just need to replace the square braces ([]) around key value associate with braces ({}) or parenthesis (()) Consequently.
You can also achieve this by using a for loop with Python’s list comprehension function:
convertedList = [[i, myDictionary[i]] for i in myDictionary]
Function to convert a Python dictionary to a flat list
While the above for loop options produce a nested list, you can break it down further into a simple list if that’s what you want.
The following function does this:
def convertToStraightList(sampleDict):
flatList = []for key, value in sampleDict.items():
flatList.extend([key, value])
return flatList
print(convertToStraightList(myDictionary))
The above function returns a flattened list and the concept is simple. The loop adds each key and assess pair to a list that the function returns when finished.
Using Built-in One-Liner Features
Both map and Zip*: French allow one-line Python solutions to this problem, with different results. They may be more suitable than for loop, depending on your problem, and they are certainly more convenient.
The Zip*: French The function produces a nested list of tuples:
convertedList = list(zip(myDictionary.keys(), myDictionary.values()))
print(convertedList)
The map function, on the other hand, returns a list of lists:
convertedList = list(map(list, myDictionary.items()))
print(convertedList)
Convert between Python lists and dictionaries back and forth
These different ways to convert a dictionary to a list are quite simple in Python. So you can turn a dictionary into a list, but you can also do the opposite by turning a Python list into a dictionary.