Open In App

Get Values from Dictionary Using For Loop - Python

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, dictionaries store data as key-value pairs and we are given a dictionary. Our task is to extract its values using a for loop, this approach allows us to iterate through the dictionary efficiently and retrieve only the values. For example, given d = {'a': 1, 'b': 2, 'c': 3}, we should extract [1, 2, 3]. This can be achieved in multiple ways as given below:

Using .values()

The most efficient way to extract values from a dictionary is by using the .values() method which directly returns all values in an iterable format. This allows us to loop through them without needing to access keys manually.

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

for val in d.values():  
    print(val)  

Output
1
2
3

Explanation:

  • d.values() retrieves all values from the dictionary without iterating over the keys and the for loop then goes through each value one by one and prints it
  • this method is both simple and efficient as it avoids unnecessary key lookups.

Using List Comprehension

List comprehension provides a compact way to extract and store dictionary values in a list and this is useful when we need to process or manipulate the values later.

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

a = [val for val in d.values()]  
print(a)  

Output
[1, 2, 3]

Explanation:

  • d.values() retrieves all dictionary values and [val for val in d.values()] iterates through them storing each value in a list.
  • result is printed as [1, 2, 3], making this approach efficient for collecting values in a single step.

Using .items() Method

.items() method returns both keys and values but we can extract only the values while iterating.

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

# Using items() method
for key, val in d.items():  
    print(val)  

Output
1
2
3

Explanation: d.items() returns key-value pairs but since we only need values so we unpack each pair into key, val and print val whhile slightly less efficient than .values(), this approach is useful when both keys and values are needed.

Iterating Directly Over Dictionary

By default, looping over a dictionary iterates through its keys which we can then use to access values.

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

for key in d:  
    print(d[key])  

Output
1
2
3

Explanation: the loop iterates over d’s keys and d[key] retrieves the corresponding value.


Next Article
Practice Tags :

Similar Reads