![]() |
VOOZH | about |
We are given a list of dictionaries and a particular key. Our task is to retrieve the values associated with that key from each dictionary in the list. If the key doesn't exist in a dictionary, it should be ignored. For example, if we have the following list of dictionaries and we want to extract the values for the key 'aryan': li = [{'aryan': 10, 'harsh': 20}, {'aryan': 30, 'kunal': 40}, {'harsh': 50}] then the output will be [10, 30].
We use List comprehension to iterate over the list of dictionaries and retrieve the values associated with the particular key. If the key exists in the dictionary then the value will be appended to the result list.
[10, 30]
Explanation:
We can use map() function to extract the key values directly after filtering the dictionaries that have the key using filter() function.
[10, 30]
Explanation:
In this method we use a for loop to manually iterate over the list of dictionaries and check for the key, if present then collect the values and store in result.
[10, 30]
Explanation: