I’m trying to check if a combination of two key-value pairs exists in list of dictionaries. Here is my list.
data =
[
{'transaction':'abc123', 'stage_one':'Started', 'stage_two':'Complete', 'version': 12),
{'transaction':'abc123', 'stage_one':'Started', 'stage_two':'started', 'version': 12),
{'transaction':'abc123', 'stage_one':'Started', 'stage_two':'processing', 'version': 12),
{'transaction':'abc123', 'stage_one':'Started', 'stage_two':'Complete', 'version': 12)
]
I have tried the below line of code, but I always get values exists when invalid combinations of data is checked. Can someone please shed some light on this issue?
if not any((d['stage_one'] ==('Started') and d['stage_two'] ==
('Complete123')) for d in data):
print("values exists")
else:
print("values don't exists")
>Solution :
I would use a list comprehension on your list of dictionaries, with a conditional statement:
results = [d for d in data if d['stage_one'] =='some_value' and d['stage_two'] == 'some_other_value']
if len(results) > 0:
print("values exists")
else:
print("values don't exists")
This way, you can also check how many matches you have by looking at the length of results