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

Compare two dictionaries and get the differences with Python

I’m using Odoo and I would like to make a comparison between two dictionaries without using any library. This comparison should return a dictionary with the differences. So here are my two dictionaries :

list1 = {
    'Office Furniture':
    [
        {
            'name': 'Office chairs can harm your floor: protect it.',
            'qty': 3
        },
    ]
}


list2 = {
    'Office Furniture': 
    [
        {
            'name': 'Office chairs can harm your floor: protect it.', 
            'qty': 3
        }, 
        {
            'name': '160x80cm, with large legs.', 
            'qty': 1
        }
    ], 
    'Services': 
    [
        {
            'name': 'designing', 
            'qty': 1
        }
    ]
}

I would like, without any library, to got the differences between those two dictionaries like this:

differences = {
   'Office Furniture':
   [
       {
           'name': '160x80cm, with large legs.',
           'qty': 1
       }
   ],

   'Services':
   [
       {
           'name': 'designing',
           'qty': 1
       }
   ]
}

Thanks a lot for your help !

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 :

This code iterates through each key-value pair in list2. For each key, it checks two cases.

CASE I: if the key exists in list1 or not. If it doesn’t, then it adds the entire value list to the differences dictionary under the same key.

CASE II: If the key exists in both list1 and list2 then it will iterate through each item in the value list. For each item, it checks if the item exists in the corresponding list in list1. If it doesn’t, it adds that item to the differences dictionary under the same key.

for key, value in list2.items():
    # Check if the key exists in list1
    if key not in list1:
        differences[key] = value
    else:
        # Check each item in the value list
        for item in value:
            # Check if the item exists in list1
            if item not in list1[key]:
                if key not in differences:
                    differences[key] = []
                differences[key].append(item)
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