Python | Find dictionary matching value in list
The problem of getting only the suitable dictionary that has a particular value of the corresponding key is quite common when one starts working with a dictionary in Python. Let’s discuss certain ways in which this task can be performed.
Method 1: Get a list of values from a List of Dictionary using a loop
This is the brute force method by which this task can be performed. For this, we just use naive check and compare and return the result once we find the suitable match and break for the rest of the dictionaries.
Python3
# Initialize list test_list = [ { 'Course' : "C++" , 'Author' : "Jerry" }, { 'Course' : "Python" , 'Author' : "Mark" }, { 'Course' : "Java" , 'Author' : "Paul" }] # Find dictionary matching value in list res = None for sub in test_list: if sub[ 'Author' ] = = "Mark" : res = sub break # printing result print ( "The filtered dictionary value is : " + str (res)) |
Output :
The filtered dictionary value is : {'Course': 'Python', 'Author': 'Mark'}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Get a list of values from a List of Dictionary using next() + dictionary comprehension
The combination of these methods can also be used to perform this task. This difference is that it’s a one-liner and more efficient as the next function uses an iterator as an internal implementation which is quicker than generic methods.
Python3
# Initialize list test_list = [ { 'Course' : "C++" , 'Author' : "Jerry" }, { 'Course' : "Python" , 'Author' : "Mark" }, { 'Course' : "Java" , 'Author' : "Paul" }] # Find dictionary matching value in list res = next ((sub for sub in test_list if sub[ 'Course' ] = = "Java" ), None ) # printing result print ( "The filtered dictionary value is : " + str (res)) |
Output:
The filtered dictionary value is : {'Course': 'Java', 'Author': 'Paul'}
Method 3: Get a list of values from a List of Dictionary using a list comprehension
In this method, we are simply using a function and passing the name we want to search and the test_list and with the help of list comprehension, we return the list.
Python3
test_list = [ { 'Course' : "C++" , 'Author' : "Jerry" }, { 'Course' : "Python" , 'Author' : "Mark" }, { 'Course' : "Java" , 'Author' : "Paul" }] def search(name, test_list): return [element for element in test_list if element[ 'Author' ] = = name] res = search( "Paul" , test_list) print (res) |
Output:
[{'Course': 'Java', 'Author': 'Paul'}]
Method 4: Get a list of values from a List of Dictionary using a filter method
In this method, we are filtering our required result using the Python filter method, and then implicating it into a Python list().
Python3
test_list = [ { 'Course' : "C++" , 'Author' : "Jerry" }, { 'Course' : "Python" , 'Author' : "Mark" }, { 'Course' : "Java" , 'Author' : "Paul" }] res = list ( filter ( lambda test_list: test_list[ 'Author' ] = = 'Jerry' , test_list)) print (res) |
Output:
[{'Course': 'C++', 'Author': 'Jerry'}]
Please Login to comment...