Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if two key value pairs exists in list of Dictionary in Python

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading