Reputation: 5938
Using python 2.7 what would be the proper approach to return only what is different from a set of dictionaries on two different lists? The code bellow is works, but I'm sure there's a better way to do it but I'm not sure how it could be achieved.
l_current = [{'type': 'food', 'drink': 'water'},{'type': 'food', 'drink': 'other'}]
l_new = [{'type': 'food', 'drink': 'other'},
{'type': 'food', 'drink': 'dirt'},
{'type': 'food', 'drink': 'gasoline'}]
l_final = []
for curr in l_current:
for new in l_new:
nkey = new['propertie_key']
ckey = curr['propertie_key']
nval = new['propertie_value']
cval = curr['propertie_value']
if nkey == ckey:
if nval != cval:
d_final = {nkey: nval}
l_final.append(d_final)
Desired Output It would be only what is different from the l_new regarding l_current:
[{'type': 'food', 'drink': 'dirt'},{'type': 'food', 'drink': 'gasoline'}]
Edit: It's not a homework, I'm just trying to optimize a current working code.
Edit 2: The desired output is already there, After some searching on google I was able to find some solutions like the following ones, but I'm not sure how could i implement it.
remove-duplicate-dict-in-list-in-python
how-to-subtract-values-from-dictionaries
Upvotes: 0
Views: 79
Reputation: 383
From your given example you can achieve the desired result in a list comprehension:
l_final = [item for item in l_new if item not in l_current]
This should check each item in the new list and store it in the final list if the current list element is not present.
Upvotes: 1
Reputation: 15204
If I understand this correctly it is as simple as that:
l_current = [{'type': 'food', 'drink': 'water'},{'type': 'food', 'drink': 'other'}]
l_new = [{'type': 'food', 'drink': 'other'},
{'type': 'food', 'drink': 'dirt'},
{'type': 'food', 'drink': 'gasoline'}]
l_final = [x for x in l_new if x not in l_current]
print(l_final) # [{'drink': 'dirt', 'type': 'food'}, {'drink': 'gasoline', 'type': 'food'}]
You can compare dictionaries the same way you compare any other object in Python and that is the reason the above list comprehension works; testing for membership boils down to an equality check.
Upvotes: 4