![]() |
VOOZH | about |
Our task is to retrieve values associated with specific keys from a dictionary. This is especially useful when we only need to access certain pieces of data rather than the entire dictionary. For example, suppose we have the following dictionary: d = {'name': 'John', 'age': 25, 'location': 'New York', 'job': 'Engineer'} if we need to get the values for the keys 'name' and 'job' then the output should be: {'name': 'John', 'job': 'Engineer'}
We can use dictionary comprehension to achieve a more compact version of the loop method.
{'name': 'John', 'job': 'Engineer'}
Explanation:
We can iterate through the dictionary and check if the key exists then retrieve its value. This is a simple approach to get specific values based on the keys.
{'name': 'John', 'job': 'Engineer'}
Explanation: We define a list filter_key that contains the keys whose values we want to retrieve and then loop through each key in this list, if the key is present in the dictionary then we add the key-value pair to the result dictionary.
filter() function can also be used to filter out keys that we want to retrieve from the dictionary. It’s more functional in style and allows us to process the keys more flexibly.
{'name': 'John', 'job': 'Engineer'}
Explanation:
map() function can be used to apply a function to each item in an iterable allowing us to process the keys in the dictionary. We can then filter out the values for the specified keys.
{'name': 'John', 'job': 'Engineer'}
Explanation: