-1

I'm looking to find the diff between two dictionaries.

[Dict. 1]
{"1":"w"},
{"2":"x"},
{"3":"y"}

[Dict. 2]
{"2":"b"},
{"3":"y"},
{"4":"z"}

I want to find the diff that will transform Dict. 2 into a dictionary that is identical to Dict. 1

I am not allowed to set Dict. 2 equal to Dict. 1.

I can only modify Dict. 2 by using the least number of add/update/remove actions possible. For the above example, my diff should look like.

[Dict. 2]      [Diff]              [Dict. 2]
{"2":"b"},     add("1","w")        {"1":"w"},
{"3":"y"},  +  update("2","x")  =  {"2":"x"},
{"4":"z"}      remove("4")         {"3":"y"}

Using Python, how can I find the diff for these two dictionaries? My diff needs to contain the least number adds, updates, and removes.

Ko Junki
  • 11
  • 3
  • Welcome to StackOverflow. [On topic](https://stackoverflow.com/help/on-topic), [how to ask](https://stackoverflow.com/help/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. StackOverflow is a knowledge base for *specific* programming problems -- not a design, coding, research, or tutorial resource. If you search in your browser for "Find list differences", you'll find references that can explain this much better than we can manage here. – Prune Dec 19 '19 at 19:17
  • @TrentonMcKinney While it solves part of my problem, the difference it creates does not retain enough information on its own to help me create the diff I'm looking for – Ko Junki Dec 19 '19 at 19:36

1 Answers1

1

You could try working with set differences:

def transform_dicts(a, b):
    extra = set(dict_2.items()) - set(dict_1.items())
    missing = set(dict_1.items()) - set(dict_2.items())

    for key, val in extra:
        del b[key]

    for key, val in missing:
        b[key] = val

    return b

It's not particularly terse but it will take few operations to complete.

Philip Ciunkiewicz
  • 2,652
  • 3
  • 12
  • 24