How to Get Values from Dictionary in Python using For Loop?
- Using
values()
Method - Iterating Directly Over Dictionary
- Using
items()
Method - Using List Comprehension
Get Values from Dictionary in Python Using values()
Method
In this example, the below code defines a dictionary `my_dict` with information. The `for` loop, using `values()`, prints each value, allowing easy access and display of the dictionary’s data.
Python3
# Dictionary my_dict = { 'name' : 'Geeks' , 'age' : 20 , 'city' : 'India' } # Using values() method for value in my_dict.values(): print (value) |
Geeks 20 India
Get Values from Dictionary in Python Iterating Directly Over Dictionary
In this example, below Python code initializes a dictionary `my_dict` and iterates directly over its keys. Inside the loop, each key is used to access the corresponding value, which is then printed to the console.
Python3
# Dictionary my_dict = { 'name' : 'Geeks' , 'age' : 20 , 'city' : 'India' } # Iterating directly over dictionary for key in my_dict: value = my_dict[key] print (value) |
Geeks 20 India
Get Values from Dictionary in Python Using items()
Method
In this Python code , the dictionary `my_dict` is defined, and the `for` loop utilizes the `items()` method to iterate through key-value pairs. The loop prints each value, allowing convenient access to and display of the dictionary’s data.
Python3
# Dictionary my_dict = { 'name' : 'Geeks' , 'age' : 20 , 'city' : 'India' } # Using items() method for key, value in my_dict.items(): print (value) |
Geeks 20 India
Get Values from Dictionary in Python Using List Comprehension
In this example, below Python code defines a dictionary `my_dict` and employs list comprehension to create a list of values by iterating through its keys. The subsequent `for` loop then prints each value, providing a concise way to access and display the dictionary’s data.
Python3
# Dictionary my_dict = { 'name' : 'Geeks' , 'age' : 20 , 'city' : 'India' } # Using list comprehension values = [my_dict[key] for key in my_dict] for value in values: print (value) |
Geeks 20 India
Conclusion
In conclusion, retrieving values from a dictionary in Python using a for
loop can be accomplished through various methods. Whether utilizing the values()
method, iterating directly over the dictionary, using the items()
method, or employing list comprehension, Python offers flexibility in accessing and utilizing dictionary values. Choose the method that aligns with your preferences and specific requirements.
Get Values from Dictionary in Python Using For Loop
Dictionaries in Python are versatile data structures that allow you to store and retrieve key-value pairs efficiently. Accessing the values within a dictionary is a common operation, and Python provides multiple ways to achieve this using a for
loop. In this article, we will explore some commonly used methods to extract values from a dictionary using a for
loop, along with their syntax.