Python - Check List elements from Dictionary List
Last Updated :
29 Mar, 2023
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.
Python3
# Python3 code to demonstrate working of
# Check List elements from Dictionary List
# Using loop
# helpr_func
def check_ele(ele, test_list):
for sub in test_list:
for item in sub.values():
if ele == item:
return True
return False
# initializing list
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'}]
# printing original list
print("The original list is : " + str(test_list))
# initializing Values list
val_list = ['Yellow', 'Red', 'Orange', 'Green']
# Check List elements from Dictionary List
# Using loop
res = []
for ele in val_list:
res.append(check_ele(ele, test_list))
# printing result
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().
Python3
# Python3 code to demonstrate working of
# Check List elements from Dictionary List
# Using any() + generator expression
# initializing list
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'}]
# printing original list
print("The original list is : " + str(test_list))
# initializing Values list
val_list = ['Yellow', 'Red', 'Orange', 'Green']
# initializing Key
key = 'Color'
# Check List elements from Dictionary List
# Using loop
res = [any(clr == sub[key] for sub in test_list) for clr in val_list]
# printing result
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]
Using the set function and a list comprehension:
Approach:
We can convert the list of dictionaries into a set of tuples, where each tuple represents a dictionary, and use a list comprehension to generate a list of booleans indicating if each tuple matches the tuple representation of the target dictionary.
Python3
def check_list_elements_4(test_list, target_dict):
set_of_tuples = {tuple(sorted(d.items())) for d in test_list}
target_tuple = tuple(sorted(target_dict.items()))
return target_tuple in set_of_tuples
test_list = [{'Price': 20, 'Color': 'Orange'},
{'Price': 25, 'Color': 'Yellow'}]
check_dict = {'Price': 20, 'Color': 'Orange'}
output = check_list_elements_4(test_list, check_dict)
print(output) # [True, False, True, False]
test_list = [{'Color': 'Pink', 'Price': 50}]
check_dict = {'Price': 20, 'Color': 'Orange'}
output = check_list_elements_4(test_list, check_dict)
print(output) # [False, False, False, False]
Time complexity: O(n log n), where n is the length of test_list. The set of tuples needs to be created, which involves sorting each dictionary by its keys, so the time complexity is O(n log n). The list comprehension and in operator both have a time complexity of O(1).
Auxiliary Space: O(n), as a set of tuples needs to be created to store the dictionaries in test_list.
Similar Reads
Check if dictionary is empty in Python Sometimes, we need to check if a particular dictionary is empty or not. Python# initializing empty dictionary d = {} print(bool(d)) print(not bool(d)) d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(bool(d)) print(not bool(d)) OutputFalse True True False Different Methods to Check if a Dictionary is Em
5 min read
Python | Check if all elements in list follow a condition Sometimes, while working with Python list, we can have a problem in which we need to check if all the elements in list abide to a particular condition. This can have application in filtering in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python - Check if List contains elements in Range Checking if a list contains elements within a specific range is a common problem. In this article, we will various approaches to test if elements of a list fall within a given range in Python. Let's start with a simple method to Test whether a list contains elements in a range.Using any() Function -
3 min read
Python Check if the List Contains Elements of another List The task of checking if a list contains elements of another list in Python involves verifying whether all elements from one list are present in another list. For example, checking if ["a", "b"] exists within ["a", "b", "c", "d"] would return True, while checking ["x", "y"] would return False. Using
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
Python - Assigning Key values to list elements from Value list Dictionary Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6,
7 min read