Python | Find dictionary matching value in list
Last Updated :
18 May, 2023
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
test_list = [
{ 'Course' : "C++" , 'Author' : "Jerry" },
{ 'Course' : "Python" , 'Author' : "Mark" },
{ 'Course' : "Java" , 'Author' : "Paul" }]
res = None
for sub in test_list:
if sub[ 'Author' ] = = "Mark" :
res = sub
break
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
test_list = [
{ 'Course' : "C++" , 'Author' : "Jerry" },
{ 'Course' : "Python" , 'Author' : "Mark" },
{ 'Course' : "Java" , 'Author' : "Paul" }]
res = next ((sub for sub in test_list if sub[ 'Course' ] = = "Java" ), None )
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'}]
Method 5: Using the list.index() method
- Create a list of the ‘Course’ values in the dictionaries in the list using a list comprehension.
- Use the index() method to find the index of the target value in the list of ‘Course’ values.
- Use the index to return the matching dictionary from the original list.
- If no match is found, return None.
Python3
test_list = [
{ 'Course' : "C++" , 'Author' : "Jerry" },
{ 'Course' : "Python" , 'Author' : "Mark" },
{ 'Course' : "Java" , 'Author' : "Paul" }]
target_value = "Java"
course_list = [d[ 'Course' ] for d in test_list]
try :
index = course_list.index(target_value)
except ValueError:
index = None
if index is not None :
res = test_list[index]
else :
res = None
print ( "The filtered dictionary value is : " + str (res))
|
Output
The filtered dictionary value is : {'Course': 'Java', 'Author': 'Paul'}
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.
METHOD 6:Using defaultdict method.
APPROACH:
This code uses collections.defaultdict to create a dictionary of lists, where the keys are the values of the “Course” key and the values are lists of dictionaries that have that value. It then gets the list of dictionaries that have “Python” as the value for “Course” and returns the first one.
ALGORITHM:
1.Import the collections.defaultdict method.
2.Create a list of dictionaries test_list.
3.Create an empty defaultdict called course_dict.
4.Iterate through the test_list and append each dictionary to the list that corresponds to the value of the “Course” key in course_dict.
5.Get the list of dictionaries that have “Python” as the value for “Course”.
6.If there’s at least one dictionary in the list, return the first one.
7.If there’s no dictionary in the list, print “No matching dictionary found”.
Python3
from collections import defaultdict
test_list = [
{ 'Course' : "C++" , 'Author' : "Jerry" },
{ 'Course' : "Python" , 'Author' : "Mark" },
{ 'Course' : "Java" , 'Author' : "Paul" },
{ 'Course' : "Python" , 'Author' : "Kate" },
{ 'Course' : "Python" , 'Author' : "David" }
]
course_dict = defaultdict( list )
for d in test_list:
course_dict[d[ 'Course' ]].append(d)
filtered_list = course_dict[ 'Python' ]
if len (filtered_list) > 0 :
filtered_dict = filtered_list[ 0 ]
print (filtered_dict)
else :
print ( "No matching dictionary found" )
|
Output
{'Course': 'Python', 'Author': 'Mark'}
Time complexity:
The time complexity of this code is O(n), where n is the length of the test_list. This is because we iterate through the list once to create the defaultdict, which takes O(n) time. Then we access the list of dictionaries with “Python” as the value for “Course”, which takes O(1) time. Finally, we return the first dictionary in the list, which also takes O(1) time.
Space complexity:
The space complexity of this code is O(n), where n is the length of the test_list. This is because we create a defaultdict called course_dict that contains a list for each value of the “Course” key in the test_list. The size of course_dict is therefore proportional to the number of unique “Course” values in the test_list, which can be up to n in the worst case.
METHOD 7:Using recursion:
Algorithm:
- If the input test_list is empty, return an empty list [].
- If the first dictionary in test_list has an ‘Author’ key equal to the input name, add it to the result list along with
- the result of calling the search function recursively on the remaining elements of test_list.
- If the first dictionary in test_list does not have an ‘Author’ key equal to the input name, call the search function recursively on the remaining elements of test_list.
- Return the resulting list of dictionaries.
Python3
def search(name, test_list):
if not test_list:
return []
elif test_list[ 0 ][ 'Author' ] = = name:
return [test_list[ 0 ]] + search(name, test_list[ 1 :])
else :
return search(name, test_list[ 1 :])
test_list = [ { 'Course' : "C++" , 'Author' : "Jerry" }, { 'Course' : "Python" , 'Author' : "Mark" }, { 'Course' : "Java" , 'Author' : "Paul" }]
res = search( "Paul" , test_list)
print (res)
|
Output
[{'Course': 'Java', 'Author': 'Paul'}]
Time Complexity:
In the worst case, where the input test_list has length n and all the dictionaries in the list have a different ‘Author’ value, the search function will have to iterate over all n dictionaries in the list before returning the result. In this case, the time complexity of the function is O(n), as the recursive calls make a constant amount of work per element in the list.
Space Complexity:
The search function uses a recursive approach to search the test_list for the input name. The space complexity of this recursive function is O(n) in the worst case, where n is the length of the test_list. This is because in the worst case, the recursion depth will be equal to the length of the list, as each recursive call makes a copy of the remaining list of length n-1. Therefore, the space required to store the recursive function call stack will be proportional to n.
Similar Reads
Minimum Value Keys in Dictionary - Python
We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
4 min read
Get Python Dictionary Values as List - Python
We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5] Using itertools.chain()itertools.chain() function efficientl
2 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python | Unique dictionary filter in list
We are given a dictionary in list we need to find unique dictionary. For example, a = [ {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"c": 3}, {"a": 1, "b": 3}] so that output should be [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}, {'c': 3}]. Using set with frozensetUsing set with frozenset, we convert dictionary ite
3 min read
Element Occurrence in Dictionary of List Values - Python
We are having a dictionary of list we need to find occurrence of all elements. For example, d = {'a': [1, 2, 3, 1], 'b': [3, 4, 1], 'c': [1, 5, 6]} we need to count the occurrence of all elements in dictionary list so that resultant output should be {'a': 2, 'b': 1, 'c': 1}. Using a Dictionary Compr
3 min read
Python - Check for Key in Dictionary Value list
Sometimes, while working with data, we might have a problem we receive a dictionary whose 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() Th
6 min read
Convert Matrix to Dictionary Value List - Python
We are given a matrix and the task is to map each column of a matrix to customized keys from a list. For example, given a matrix li = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]] and a list map_li = [4, 5, 6], the goal is to map the first column to the key 4, the second column to the key 5, and the
3 min read
Python | Initializing dictionary with list index-values
While working with Python we might need to perform tasks in which we need to assign a dictionary with list values as dictionary values and index as dictionary keys. This type of problem is quite common in cases we need to perform data-type conversion. Let's discuss certain ways in which this task ca
4 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python | Test if element is dictionary value
Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it's any key's value. This can have use cases in any field of programming one can think of. Let's discuss certain ways in which this prob
4 min read