Convert Dictionary Values to a List in Python

Convert Dictionary Values to a List in Python

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Given a dictionary, the task is to convert values of this dictionary to a list.

Examples:

Example 1:

Input:

dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}

Output:

[200, 100, 300]

Example 2:

Input:

dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300 ,'python' :400}

Output:

[200, 100, 300,400]

Convert Dictionary Values to a List in Python

There are several ways to convert dictionary values to a list some of them are:

Method #1:Using list() function

A dictionary class in Python has a function values() that returns an iterable sequence of all dictionary values. The list() function will return a list containing all of the dictionary’s values if we transfer this iterable sequence(dict values) to it.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# converting values to list
valueslist = list(dictionary.values())
# print the values list
for value in valueslist:
    print(value)

Output:

[200, 100, 300]

Method #2:Using List Comprehension

We can also use this list comprehension to iterate over the values of dictionary and convert to list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# converting values to list using list comprehension
valueslist = ([value for value in dictionary.values()])
# print the values list
print(valueslist)

Output:

[200, 100, 300]

Method #3:Convert specific values of dictionary to list

Assume we want to convert only a selected values in a dictionary to a list.

As an example, consider converting values greater than 100.

We can accomplish this by iterating through the dictionary values and checking the condition.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse the dictionary values and check condition
valueslist = [value for value in dictionary.values() if value > 100]
# print the values list
print(valueslist)

Output:

[200, 300]

 
Related Programs: