Python: Check if Key and Value Exist in a List of Dictionaries
To check if a key and value exist in a list of dictionaries, you can use a loop and the 'in' operator:
my_list = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}]
for d in my_list:
if 'name' in d and 'John' in d.values():
print('Key and value found in dictionary:', d)
This code loops through each dictionary in the list and checks if the key 'name' exists and if the value 'John' exists in the dictionary's values. If both conditions are true, it prints the dictionary that contains the key-value pair.
原文地址: https://www.cveoy.top/t/topic/lNAJ 著作权归作者所有。请勿转载和采集!