Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Find dictionary matching value in list

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'}]

Method 5: Using the list.index() method

  1. Create a list of the ‘Course’ values in the dictionaries in the list using a list comprehension.
  2. Use the index() method to find the index of the target value in the list of ‘Course’ values.
  3. Use the index to return the matching dictionary from the original list.
  4. If no match is found, return None.

Python3




# Initialize list
test_list = [
    {'Course': "C++", 'Author': "Jerry"},
    {'Course': "Python", 'Author': "Mark"},
    {'Course': "Java", 'Author': "Paul"}]
 
# Define target value
target_value = "Java"
 
# Get list of 'Course' values and find index of target value
course_list = [d['Course'] for d in test_list]
try:
    index = course_list.index(target_value)
except ValueError:
    index = None
 
# Use index to get matching dictionary, or return None
if index is not None:
    res = test_list[index]
else:
    res = None
 
# printing result
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"}
]
 
# Use defaultdict to create a dictionary of lists of dictionaries, keyed by "Course" values
course_dict = defaultdict(list)
for d in test_list:
    course_dict[d['Course']].append(d)
 
# Get the list of dictionaries that have "Python" as the value for "Course"
filtered_list = course_dict['Python']
 
if len(filtered_list) > 0:
    # If there's at least one dictionary in the list, return the first one
    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:

  1. If the input test_list is empty, return an empty list [].
  2. If the first dictionary in test_list has an ‘Author’ key equal to the input name, add it to the result list along with
  3. the result of calling the search function recursively on the remaining elements of test_list.
  4. 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.
  5. 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)
#This code is contributed by Jyothi pinjala.


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.

RELATED ARTICLES

Most Popular

Recent Comments