Get list of values from a dictionary in Python

In this tutorial, you will learn how to get a list of values from a dictionary in Python.

 

Introduction:

In Python, a dictionary is a group of key-value pairs in which each key is unique. It stores pairs of objects, i.e., keys and their corresponding values, where the keys must be unique but the values can be the same. This means that every key in a dictionary must be unique inside that dictionary, but different keys can have the same value.

Here’s a step-by-step procedure for how to get a list of values from a dictionary in Python.

Initialize a Dictionary:

A dictionary in Python is like a real-world dictionary, but instead of words and their definitions, it contains a set of key-value pairs. Sometimes, you might need to extract just the values from a dictionary for processing or analysis.

my_dict = {'a': 1, 'b': 2, 'c': 3}

This line creates a dictionary with three key-value pairs. The keys are ‘a’, ‘b’, and ‘c’, and their corresponding values are 1, 2, and 3, respectively.

 

Retrieve the values from the dictionary:

The values() method is a built-in function for dictionaries in Python. Upon calling this method, it will return a view object with all the values of the dictionary in it. This view object displays any changes or modifications made to the dictionary, offering a dynamic view of its values.

The list() function is used to turn this view object into a list, and it also generates a list with every value from the dictionary.

values_list = list(my_dict.values())

Print the generated list:

To print the values in the dictionary, we use the basic print statement in Python.

print(values_list)

This line prints the list of values to the console, i.e., [1, 2, 3].

Complete Code:

my_dict = {'a': 1, 'b': 2, 'c': 3}

# List of values
values_list = list(my_dict.values())

# Print the list of values
print(values_list)

Output:

[1, 2, 3]

Overall,  this code provides a simple way to extract values from a dictionary in Python.

 

Additionally, you may also refer to:

Leave a Reply

Your email address will not be published. Required fields are marked *