![]() |
VOOZH | about |
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:
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.
1 2 3
Explanation:
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.
[1, 2, 3]
Explanation:
.items() method returns both keys and values but we can extract only the values while iterating.
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.
By default, looping over a dictionary iterates through its keys which we can then use to access values.
1 2 3
Explanation: the loop iterates over dās keys and d[key] retrieves the corresponding value.