I've a list of two dicts and compare it with deepdiff. How can I modify/overwrite the values in the dict1 with the modified values of the dict2 "in-place"?
import deepdiff
dict_1 = [{"id": "first", "name": "first"}, {"id": "second", "name": "second"}, {"id": "third", "name": "third"}]
dict_2 = [{"id": "first", "name": "first"}, {"id": "second modified", "name": "second modified"}, {"id": "third", "name": "third"}]
diff = deepdiff.DeepDiff(dict_1, dict_2).get('values_changed',{})
print(diff)
This results to:
{"root[1]['id']": {'new_value': 'second modified', 'old_value': 'second'}, "root[1]['name']": {'new_value': 'second modified', 'old_value': 'second'}}
How can I process the results of Deepdiff? The result should be:
dict_1 = [{"id": "first", "name": "first"}, {"id": "second modified", "name": "second modified"}, {"id": "third", "name": "third"}]
Abbendum: If the "in-place" replacement is not working, a newly created dict_3 would also be ok.
I've a list of two dicts and compare it with deepdiff. How can I modify/overwrite the values in the dict1 with the modified values of the dict2 "in-place"?
import deepdiff
dict_1 = [{"id": "first", "name": "first"}, {"id": "second", "name": "second"}, {"id": "third", "name": "third"}]
dict_2 = [{"id": "first", "name": "first"}, {"id": "second modified", "name": "second modified"}, {"id": "third", "name": "third"}]
diff = deepdiff.DeepDiff(dict_1, dict_2).get('values_changed',{})
print(diff)
This results to:
{"root[1]['id']": {'new_value': 'second modified', 'old_value': 'second'}, "root[1]['name']": {'new_value': 'second modified', 'old_value': 'second'}}
How can I process the results of Deepdiff? The result should be:
dict_1 = [{"id": "first", "name": "first"}, {"id": "second modified", "name": "second modified"}, {"id": "third", "name": "third"}]
Abbendum: If the "in-place" replacement is not working, a newly created dict_3 would also be ok.
Share edited Nov 22, 2024 at 6:52 snakecharmerb 56k13 gold badges132 silver badges186 bronze badges asked Nov 22, 2024 at 6:47 sarombasaromba 4982 gold badges8 silver badges24 bronze badges1 Answer
Reset to default 1It seems that Delta
from deepdiff
does what you want:
import deepdiff
dict_1 = [{"id": "first", "name": "first"}, {"id": "second", "name": "second"}, {"id": "third", "name": "third"}]
dict_2 = [{"id": "first", "name": "first"}, {"id": "second modified", "name": "second modified"}, {"id": "third", "name": "third"}]
diff = deepdiff.DeepDiff(dict_1, dict_2)
delta = deepdiff.Delta(diff, mutate=True)
dict_1 + delta
You can also use it without mutate=True
to obtain a new object:
# ...
delta = deepdiff.Delta(diff)
dict_3 = dict_1 + delta
With this you obtain the same as dict_2
. Maybe you can change the diff
to only keep the values_changed
if you are not interested in *_item_added
from the diff
.