![]() |
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 DictionariesBelow are some of the ways by which we can select only specific key-value pairs from a list of dictionaries in Python:
Select Only Specific Key-Value Pairs Using a List ComprehensionHere, 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. Python3
Output
[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}] Select Only Specific Key-Value Pairs Using for LoopThe 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. Python3
Output
[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}] Select Only Specific Key-Value Pairs Using map and lambdaThe 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. Python3
Output
[{'city': 'Hyderabad'}, {'city': 'United states'}, {'city': 'Japan'}] |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |