Check value in list of dict Python

This tutorial will introduce the methods you can use to search a list of dictionaries in Python.

Use the next[] Function to Search a List of Dictionaries in Python

The 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 "", line 8, in StopIteration

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:

None

Rather 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:

2

Search a List of Dictionaries With the filter[] Function in Python

The 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 Python

List 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

  • Compare Two Dictionaries in Python
  • Python Dictionary Index
  • Find Maximum Value in a List in Python
  • Find All the Indices of an Element in a List in Python
  • 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[]
    This is simple and most recommended way in which this task can be performed. In this, we just check for the key inside the values by iteration.

    test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} 

    print["The original dictionary is : " + str[test_dict]] 

    key = "GATE"

    res = any[key in ele for ele in test_dict['Gfg']]

    print["Is key present in nested dictionary list ?  : " + str[res]] 

    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
    The combination of above functionalities can be used to perform this task. In this, we iterate through the list using comprehension and perform key flattening and store keys. Then we check for desired key using in operator.

    test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} 

    print["The original dictionary is : " + str[test_dict]] 

    key = "GATE"

    res = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys[]]

    print["Is key present in nested dictionary list ?  : " + str[res]] 

    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.

    Input : test_list = [{‘Price’: 20, ‘Color’: ‘Orange’}, {‘Price’: 25, ‘Color’: ‘Yellow’}]
    Output : [True, False, True, False]

    Input : test_list = [{‘Color’: ‘Pink’, ‘Price’: 50}]
    Output : [False, False, False, False]

    Method #1 : Using loop
    This is brute way to solve this problem. In this, we iterate will all the dictionaries for each value from list and compare with the desired key and return True for records that possess it.

    def check_ele[ele, test_list]:

        for sub in test_list:

            for item in sub.values[]:

                if ele == item:

                    return True

        return False

    test_list = [{'Name' : 'Apple', 'Price' : 18, 'Color' : 'Red'},

                 {'Name' : 'Mango', 'Price' : 20, 'Color' : 'Yellow'},

                 {'Name' : 'Orange', 'Price' : 24, 'Color' : 'Orange'},

                 {'Name' : 'Plum', 'Price' : 28, 'Color' : 'Red'}]

    print["The original list is : " + str[test_list]]

    val_list = ['Yellow', 'Red', 'Orange', 'Green']

    res = []

    for ele in val_list:

        res.append[check_ele[ele, test_list]]

    print["The Association list in Order : " + str[res]] 

    Output :

    The original list is : [{‘Name’: ‘Apple’, ‘Color’: ‘Red’, ‘Price’: 18}, {‘Name’: ‘Mango’, ‘Color’: ‘Yellow’, ‘Price’: 20}, {‘Name’: ‘Orange’, ‘Color’: ‘Orange’, ‘Price’: 24}, {‘Name’: ‘Plum’, ‘Color’: ‘Red’, ‘Price’: 28}]

    The Association list in Order : [True, True, True, False]

    Method #2 : Using any[] + generator expression
    The use of any[] with integration with generator expression can solve this problem. In this we reduce the lines of code by reducing inner loop, by testing using any[].

    test_list = [{'Name' : 'Apple', 'Price' : 18, 'Color' : 'Red'},

                 {'Name' : 'Mango', 'Price' : 20, 'Color' : 'Yellow'},

                 {'Name' : 'Orange', 'Price' : 24, 'Color' : 'Orange'},

                 {'Name' : 'Plum', 'Price' : 28, 'Color' : 'Red'}]

    print["The original list is : " + str[test_list]]

    val_list = ['Yellow', 'Red', 'Orange', 'Green']

    key = 'Color'

    res = [any[clr == sub[key] for sub in test_list] for clr in val_list]

    print["The Association list in Order : " + str[res]] 

    Output :

    The original list is : [{‘Name’: ‘Apple’, ‘Color’: ‘Red’, ‘Price’: 18}, {‘Name’: ‘Mango’, ‘Color’: ‘Yellow’, ‘Price’: 20}, {‘Name’: ‘Orange’, ‘Color’: ‘Orange’, ‘Price’: 24}, {‘Name’: ‘Plum’, ‘Color’: ‘Red’, ‘Price’: 28}]

    The Association list in Order : [True, True, True, False]


    Article Tags :

    Python dictionary-programs

    Video liên quan

    Chủ Đề