To check if a key-value pair exists in a list of dictionaries, you can use the following Python code:

my_list = [{'name': 'John', 'age': 25}, {'name': 'Sarah', 'age': 30}]

for d in my_list:
    if 'name' in d and d['name'] == 'John':
        print('Name found in dictionary:', d)
    elif 'age' in d and d['age'] == 30:
        print('Age found in dictionary:', d)

In this example, we have a list of two dictionaries. We then iterate through each dictionary in the list and check if the key-value pair exists. If the key 'name' exists and its value is 'John', we print the dictionary containing this pair. Similarly, if the key 'age' exists and its value is 30, we print the dictionary containing this pair. If neither pair exists in any of the dictionaries, nothing will be printed.

This approach is efficient for searching through lists of dictionaries and identifying specific key-value pairs.

Python: Check if Key-Value Pair Exists in List of Dictionaries

原文地址: https://www.cveoy.top/t/topic/lNDf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录