Workout #16: DictDiff

1 min readOct 1, 2021

Write a function, dictdiff, that takes two dicts as arguments. The function returns a new dict that expresses the difference between the two dicts.

If there are no differences between the dicts, dictdiff returns an empty dict. For each key-value pair that differs, the return value of dictdiff will have a key-value pair in which the value is a list containing the values from the two different dicts. If one of the dicts doesn’t contain that key, it should contain None. The following provides some examples:

d1 = {'a':1, 'b':2, 'c':3}
d2 = {'a':1, 'b':2, 'c':4}
print(dictdiff(d1, d1))
Prints “{}”, because we’re comparing d1 with itself
print(dictdiff(d1, d2))
Prints “{'c': [3, 4]}”, because d1 contains c:3 and d2 contains c:4
d3 = {'a':1, 'b':2, 'd':3}
d4 = {'a':1, 'b':2, 'c':4}
print(dictdiff(d3, d4))
Prints “{'c': [None, 4], 'd': [3, None]}”, because d4 has c:4 and d3 has d:3
d5 = {'a':1, 'b':2, 'd':4}
print(dictdiff(d1, d5))
Prints “{'c': [3, None], 'd': [None, 4]}”, because d1 has c:3 and d5 has d:4

TRY IT YOURSELF

ANSWER

https://colab.research.google.com/drive/1IJKZ6fALguW9Dngmb8pKQAFzLLuCDUMl?usp=sharing

--

--

Abish Pius
Abish Pius

Written by Abish Pius

Data Science Professional, Python Enthusiast, turned LLM Engineer

No responses yet