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