Python Dictionary Values to List
Python Dictionary Values to List
To convert Python Dictionary values to List, you can use dict.values() method which returns a dict_values object. This object can be iterated, and if you pass it to list() constructor, it returns a list object with dictionary values as elements.
A simple code snippet to convert dictionary values to list is
valuesList = list(myDict.values())
Examples
1. Convert dictionary values to a list using dict.values()
In the following program, we have a dictionary initialized with three key:value pairs. We will use dict.values() method to get the dict_values object. We pass dict.values() as argument to list() constructor. list() returns the list of values.
Python Program
myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
valuesList = list(myDict.values())
print(valuesList)
Output
['apple', 'banana', 'cherry']
2. Convert dictionary values into a list using List Comprehension
We can also use List Comprehension to get the values of dictionary as elements of a list.
Python Program
myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
valuesList = [myDict[key] for key in myDict]
print(valuesList)
Output
['apple', 'banana', 'cherry']
3. Convert dictionary values into a list using For loop
If you are not comfortable with List comprehension, let us use Python For Loop. When you iterate over the dictionary, you get next key during each iteration. You can use this key to get the value. Define an empty list valuesList to store the values and append the value of key:value pair during each iteration in for loop.
Python Program
myDict = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
valuesList = []
for key in myDict:
valuesList.append(myDict[key])
print(valuesList)
Output
['apple', 'banana', 'cherry']
Summary
In this tutorial of Python Examples, we learned how to get Dictionary values as List.