Sunday, September 22, 2024
Google search engine
HomeLanguagesHow can to get list of values from dictionary in Python?

How can to get list of values from dictionary in Python?

In this article, we will discuss how to get a list of values from a dictionary using Python.

Get list of values from dictionary using values() function

We can use a dictionary.values() along with the list() function to get the list. Here, the values() method is a dictionary method used to access the values from the key: value pairs and we are then converting the values to a list by using the list() function

Python3




# create a dictionary
data = {'manoja': 'java', 'tripura': 'python',
        'manoj': 'statistics', 'manoji': 'cpp'}
 
# get list of values
list(data.values())


Output:

['java', 'python', 'statistics', 'cpp']

Get a list of values from a dictionary using a single asterisk( * ) and values() function

We can use [] along with * to get all list of dictionary values. Here values() is a dictionary method used to get the values from the key: value pair in the dictionary and * is used to get only values instead of getting dict_values and then we are getting into a list by using the list() function

Python3




data = {'manoja': 'java', 'tripura': 'python',
        'manoj': 'statistics', 'manoji': 'cpp'}
 
# get list of values
[*data.values()]


Output:

['java', 'python', 'statistics', 'cpp']

Get a list of values from a dictionary using a loop

In this method, we will use a Python loop to get the values of keys and append them to a new list called values and then we print it.

Python3




# create a dictionary
data = {'manoja': 'java', 'tripura': 'python',
        'manoj': 'statistics', 'manoji': 'cpp'}
key = ["manoj", "manoji", "tripura"]
 
# get list of values using loop
value = []
for idx in key:
    value.append(data[idx])
 
print(value)


Output:

['statistics', 'cpp', 'python']

Get a list of values from a dictionary using List comprehension

Using List comprehension we can get the list of dictionary values. Here we are using a list comprehension to iterate in a dictionary by using an iterator. This will return each value from the key: value pair.

Python3




data = {'manoja': 'java', 'tripura': 'python',
        'manoj': 'statistics', 'manoji': 'cpp'}
 
# get list of values using comprehension
[data[i] for i in data]


Output:

['java', 'python', 'statistics', 'cpp']

Get a list of values from a dictionary using the map method

In this method, we will use a Python map method to get the values of keys and convert them to a list, and then print it.

Python3




# create a dictionary
data = {'manoja': 'java', 'tripura': 'python',
        'manoj': 'statistics', 'manoji': 'cpp'}
key = ["manoj", "manoji", "tripura"]
 
# get list of values using map
value = list(map(data.get, keys))
 
print(value)


Output:

['statistics', 'cpp', 'python']

RELATED ARTICLES

Most Popular

Recent Comments