In this article, we will discuss different ways to convert all values of a python dictionary to a list.

Table of Contents

Convert all values of dictionary to list using list()

In Python, a dictionary class provides a function values(), which returns an iterable sequence of all values of dictionary. We can pass this iterable sequence(dict_values) to the list() function, it will return a list containing all values of the dictionary. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# Convert all values in dictionary to a list
list_of_values = list(word_freq.values())

print(list_of_values)

Output:

[56, 23, 43, 78, 89, 51, 79]

We created a list of all values of the dictionary.

Convert values of dictionary to list using List Comprehension

In Python, dictionary class provides a function items(), which returns an iterable sequence (dict_items) of all key-value pairs of dictionary. We can use the list comprehension to iterate over this sequence containing all items of the dictionary and create a list of values only. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# Convert all values in dictionary to a list
list_of_values = [  value 
                    for key, value in word_freq.items()]

print(list_of_values)

Output:

[56, 23, 43, 78, 89, 51, 79]

We created a list of all values of the dictionary.

In both the above examples, we converted all values of dictionary to list. But what if we want to convert only specific values from a dictionary to list? Let’s see how to do that,

Convert specific values of dictionary to list

Suppose we want to convert only selected values from a dictionary to a list. Like, select only those values of dictionary whose key is a string of length 4 or more and create a list of those values only. To achieve that, we can apply an if condition while iterating over pairs of dictionary and select only those values where condition returns the True. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# Convert dictionary values to list where key
# is a string of length greater than 4
selected_values = [ value 
                    for key, value in word_freq.items()
                    if len(key) >= 4]

print(selected_values)

Output:

[56, 43, 78]

We converted only those values to list where size of the key string is greater than 4.

Summary:

We learned about different ways to convert all or selected values of a dictionary to a list.