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

Dictionary Comparison/Conditional check in Python

I have two list of dictionaries in the format:

list1 = [{"time": "2024-01-29T18:32:24.000Z", "value": "abc"}, {"time": "2024-01-30T19:47:48.000Z", "value": "def"}, {"time": "2024-01-30T19:24:20.000Z", "value": "ghi"}]

list2 = [{"time": "2024-01-30T18:34:44.000Z", "value": "xyz"}, {"time": "2024-01-30T19:47:48.000Z", "value": "pqr"}, {"time": "2024-01-30T19:24:20.000Z", "value": "jkl"}]

Requirement : I need to compare value of "time" key of each dictionary in list1 with "time" key of each dictionary in list2 and if they are equal, will need to form a key value pair dictionary for subsequent lookups.
In the above, list1 and list2 have 2 dictionaries with same time :
"2024-01-30T19:47:48.000Z"
"2024-01-30T19:24:20.000Z"
I need to combine value of these 2 to form output as below :

Output :

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

{"def" : "pqr", "ghi" : "jkl"}

using itertools.product function , i am able to list as below so far but not in the key value pair dictionary as required .

import itertools

list1 = [{"time": "2024-01-29T18:32:24.000Z", "value": "abc"}, {"time": "2024-01-30T19:47:48.000Z", "value": "def"}, {"time": "2024-01-30T19:24:20.000Z", "value": "ghi"}]
list2 = [{"time": "2024-01-30T18:34:44.000Z", "value": "xyz"}, {"time": "2024-01-30T19:47:48.000Z", "value": "pqr"}, {"time": "2024-01-30T19:24:20.000Z", "value": "jkl"}]

output = [f"{x['value']} : {y['value']}"  if x['time'] == y['time'] else None for (x, y) in itertools.product(list1, list2)]
print(output)

Current Output :

[None, None, None, None, 'def : pqr', None, None, None, 'ghi : jkl']

I’m wondering if i can use lambda function to achieve output as : {"def" : "pqr", "ghi" : "jkl"}
Any help or suggestions is appreciated.

>Solution :

dict comprehension has an if clause (at the end), to also filter out elements, like this:

output = {x['value']: y['value'] for x, y in itertools.product(list1, list2) if x['time'] == y['time']}

Output:

{'def': 'pqr', 'ghi': 'jkl'}

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