Open In App

Select Only Specific Key-Value Pairs From a List of Dictionaries

We can select only specific key-value pair from a list of dictionaries by filtering the given dictionaries using any key. If key is present in the dictionary, then it will return the key-value pair. In this article, we will see how we can select only a specific key-value pair from a list of dictionaries. Below is an example showing the input and output of the program.

Select Only Specific Key-Value Pairs From A List Of Dictionaries

Below are some of the ways by which we can select only specific key-value pairs from a list of dictionaries in Python:



  1. Using a List Comprehension
  2. Using for Loop
  3. Using map and lambda

Select Only Specific Key-Value Pairs Using a List Comprehension

Here, we are checking whether the entered key is present in a dictionary or not using list comprehension method and returning the key-value pair of the matched key if exists in the dictionary.




list_of_dicts = [
    {'name': 'improvement', 'letters': 25, 'city': 'Hyderabad'},
    {'name': 'geeksforgeeks', 'letters': 30, 'city': 'United states'},
    {'name': 'author', 'letters': 22, 'city': 'Japan'}] 
 
selected_key = 'city'
 
selected_pairs = [{selected_key: d[selected_key]} for d in list_of_dicts]
print(selected_pairs)

Output

[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}]


Select Only Specific Key-Value Pairs Using for Loop

The for loop iterates the dictionaries present in the list. If condition checks the whether given key is present in the dictionary or not. If it present in the dictionary, then it will return the key-value pair of the matched key. If it is not present in the dictionary, it will not print anything.




list_of_dicts = [
    {'name': 'improvement', 'letters': 25, 'city': 'Hyderabad'},
    {'name': 'geeksforgeeks', 'letters': 30, 'city': 'United states'},
    {'name': 'author', 'letters': 22, 'city': 'Japan'}]
 
selected_key = 'city'
 
selected_pairs = []
for d in list_of_dicts:
    if selected_key in d:
        selected_pairs.append({selected_key: d[selected_key]})
print(selected_pairs)

Output
[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}]


Select Only Specific Key-Value Pairs Using map and lambda

The lambda expression filter the dictionaries in list of dictionaries where key is present. If key is present then map() function retrieve the key-value pair of the matched key from each dictionary and result of map function is converted in to list using list() function.




list_of_dicts = [
    {'name': 'improvement', 'letters': 25, 'city': 'Hyderabad'},
    {'name': 'geeksforgeeks', 'letters': 30, 'city': 'United states'},
    {'name': 'author', 'letters': 22, 'city': 'Japan'}]
 
selected_key = 'city'
 
selected_pairs = list(map(lambda d: {selected_key: d[selected_key]}, list_of_dicts))
print(selected_pairs)

Output
[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}]



Article Tags :