Hard: Advanced Interview · Problem 66 of 82

Dictionary Diff

HardDictionaries and SetsPython

Write dict_diff(old, new) that compares two dictionaries and returns a dictionary with three entries:

  • "added": a dictionary of the keys that are only in new, with their values,
  • "removed": a dictionary of the keys that are only in old, with their old values,
  • "changed": a dictionary of the keys in both whose value differs, mapping the key to the tuple (old_value, new_value).

Keys with equal values are not reported.

Understand the problem

Use set operations on the keys.

What is {"a": 1, "b": 2}.keys() - {"b": 3, "c": 4}.keys()? Type the set.

Dictionary key views support set operations. - gives the keys in the first but not the second: the removed keys, {"a"}.

What is {"a": 1, "b": 2}.keys() & {"b": 3, "c": 4}.keys()?

& gives the keys in both: {"b"}. Those are the only keys that can have changed.

Write the solution

Return the three-part report.

def dict_diff(old, new):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which keys are only in one dictionary, and which are in both? For the ones in both, what makes a change?

Hint 2: the shape of the answer

Use new.keys() - old.keys(), old.keys() - new.keys() and old.keys() & new.keys(). For the common keys keep only those where old[k] != new[k].

Reflect

Solution

def dict_diff(old, new):
    return {
        "added": {k: new[k] for k in new.keys() - old.keys()},
        "removed": {k: old[k] for k in old.keys() - new.keys()},
        "changed": {k: (old[k], new[k]) for k in old.keys() & new.keys() if old[k] != new[k]},
    }

What this tests: dictionary key views and their set operators, dictionary comprehensions, and comparing values.

Key views behave like sets. old.keys() - new.keys() needs no conversion to set. This is the neat way to compare dictionaries.

A value changed to None is still a change. Comparing with != (not with truthiness) handles values such as 0, "" and None correctly. A test like if old[k] and new[k] would not.

In practice this is how config files, API responses and database rows are compared; deepdiff is a library that does it recursively.

Cost: O(n + m).

What an interviewer might ask next: Make it recursive for nested dictionaries. (When both values are dictionaries, call dict_diff on them.)