Skip to content
Advertisement

Recursive diff of two dictionaries (keys and values)?

So I have a python dictionary, call it d1, and a version of that dictionary at a later point in time, call it d2. I want to find all the changes between d1 and d2. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs to be recursive. This is what I have so far:

JavaScript

It works just fine unless the value is a list. I cant quite come up with an elegant way to deal with lists, without having a huge, slightly changed version of this function repeated after a if(type(d2) == list).

Any thoughts?

EDIT: This differs from this post because the keys can change

Advertisement

Answer

One option would be to convert any lists you run into as dictionaries with the index as a key. For example:

JavaScript

JavaScript

Here is the output with the sample dictionaries you gave in comments:

JavaScript

Note that this will compare index by index, so it will need some modification to work well for list items being added or removed.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement