Open In App

How to Access Dictionary Values in Python Using For Loop

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A dictionary is a built-in data type in Python designed to store key-value pairs of data. The most common method to access values in Python is through the use of a for loop. This article explores various approaches to accessing values in a dictionary using a for loop.

Access Dictionary Values in Python Using For Loop

Below, we are explaining the examples for How to Access Dictionary Values in Python Using For Loop. Those are the following.

Access Dictionary Values

In this example, the below code defines a dictionary called “lang” with programming languages as keys and corresponding skill levels as values. Then, it iterates through the keys of the dictionary using a for-loop.

Python3




lang = {
  "python":5,
  "C++":3,
  "JavaScript":4,
  "C":2
}
for key in lang:
  print(lang[key])


Output :

5
3
4
2

Access Dictionary Values Using Dictionary.items( )

In this example, below code iterates through the items (key-value pairs) in the “lang” dictionary using a for loop and prints the values (skill levels) for each programming language.

Python3




lang = {
  "python":5,
  "C++":3,
  "JavaScript":4,
  "C":2
}
  
for key,val in lang.items():
  print(val)


Output

5
3
4
2


Access Dictionary Values Using List Comprehension

In this example, below code creates a dictionary called “lang” with programming languages as keys and skill levels as values. Then, it uses a list comprehension to extract the skill levels and assigns them to a list called “val.

Python3




lang = {
  "python":5,
  "C++":3,
  "JavaScript":4,
  "C":2
}
  
val = [ lang[key] for key in lang ]
print(val)


Output :

[5, 3, 4, 2]

Conclusion

In Conclusion, The values of the dictionary can be accessed by all these methods. Each of the methods has its own pros and cons. The programmer needs to choose which is more suitable for their operations. for example, if the values need to be filtered , list comprehension method is more suitable. likewise , it has to be selected. By knowing these techniques we can control dictionary more efficiently.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads