Check value in list of dict Python
This tutorial will introduce the methods you can use to search a list of dictionaries in Python. Show Use the next() Function to Search a List of Dictionaries in PythonThe next() function can be utilized to provide the result as the next item in the given iterator. This method also requires the use of the for loop to test the process against all the conditions. The following code uses the next() function to search a list of dictionaries in Python. lstdict = [ { "name": "Klaus", "age": 32 }, { "name": "Elijah", "age": 33 }, { "name": "Kol", "age": 28 }, { "name": "Stefan", "age": 8 } ] print(next(x for x in lstdict if x["name"] == "Klaus")) print(next(x for x in lstdict if x["name"] == "David"))Output: {'name': 'Klaus', 'age': 32} Traceback (most recent call last): File "This method is successfully implemented when we search for a name that already exists in the list of dictionaries. Still, it gives a StopIteration error when a name that doesn’t exist in the list of dictionaries is searched. However, this problem can be easily treated in the code above. You simply tweak and provide a default with the use of a slightly different API. lstdict = [ { "name": "Klaus", "age": 32 }, { "name": "Elijah", "age": 33 }, { "name": "Kol", "age": 28 }, { "name": "Stefan", "age": 8 } ] print(next((x for x in lstdict if x["name"] == "David"), None))Output: NoneRather than finding the item itself, we can also find the item’s index in a List of Dictionaries. To implement this, we can use the enumerate() function. The following code uses the next() function and the enumerate() function to search and find the item’s index. lstdict = [ { "name": "Klaus", "age": 32 }, { "name": "Elijah", "age": 33 }, { "name": "Kol", "age": 28 }, { "name": "Stefan", "age": 8 } ] print(next((i for i, x in enumerate(lstdict) if x["name"] == "Kol"), None))Output: 2Search a List of Dictionaries With the filter() Function in PythonThe filter(function, sequence) function is used to compare the sequence with the function in Python. It checks each element in the sequence to be true or not according to the function. We can easily search a list of dictionaries for an item by using the filter() function with a lambda function. In Python3, the filter() function returns an object of the filter class. We can convert that object into a list with the list() function. The following code example shows us how we can search a list of dictionaries for a specific element with the filter() and lambda functions. listOfDicts = [ { "name": "Tommy", "age": 20 }, { "name": "Markus", "age": 25 }, { "name": "Pamela", "age": 27 }, { "name": "Richard", "age": 22 } ] list(filter(lambda item: item['name'] == 'Richard', listOfDicts))Output: [{'age': 22, 'name': 'Richard'}]We searched the list of dictionaries for the element where the name key is equal to Richard by using the filter() function with a lambda function. First, we initialized our list of dictionaries, listOfDicts, and used the filter() function to search the values that match the lambda function lambda item: item['name'] == 'Richard' in it. Finally, we used the list() function to convert the results into a list. Use List Comprehension to Search a List of Dictionaries in PythonList comprehension is a relatively shorter and very graceful way to create lists that are to be formed based on the given values of an already existing list. We can use list comprehension to return a list that produces the results of the search of the list of dictionaries in Python. The following code uses list comprehension to search a list of dictionaries in Python. lstdict = [ { "name": "Klaus", "age": 32 }, { "name": "Elijah", "age": 33 }, { "name": "Kol", "age": 28 }, { "name": "Stefan", "age": 8 } ] print([x for x in lstdict if x['name'] == 'Klaus'][0])Output: {'name': 'Klaus', 'age': 32}DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page. Related Article - Python Dictionary
Sometimes, while working with data, we might have a problem we receive a dictionary whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let’s discuss certain ways in which this task can be performed. Method #1 : Using any()
Output : The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3} Is key present in nested dictionary list ? : True Method #2 : Using list comprehension + in operator
Output : The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3} Is key present in nested dictionary list ? : True Article Tags : Python dictionary-programs
Sometimes, while working with data, we can have a problem in which we need to check for list element presence as a particular key in list of records. This kind of problem can occur in domains in which data are involved like web development and Machine Learning. Lets discuss certain ways in which this task can be solved.
Method #1 : Using loop
Output :
Method #2 : Using any() + generator expression
Output :
Article Tags : Python dictionary-programs |