Thursday, October 27, 2016

SimpleDictDiffer.py when deepdiff is too much

Working with Python for the past 3 months coming from Java has been interesting (grossly understated).

Anyhow, I found myself needing a way to find the stuff (not just difference) between two dictionaries and a quick google led me to deepdiff by Sep Dehpour. It was good but found it a tad overkill for what I was doing. So another round of google and stackoverflow allowed me to cobble together this:

class SimpleDictDiffer(object):
    """
    Calculate the difference between two dictionaries as:
    (1) items added
    (2) items removed
    (3) keys same in both but changed values
    (4) keys same in both and unchanged values
    """

    def __init__(self, first_dict, second_dict):
        self.current_dict, self.past_dict = first_dict, second_dict
        self.set_current, self.set_past = set(first_dict.keys()), set(second_dict.keys())
        self.intersect = self.set_current.intersection(self.set_past)

    def added(self):
        return self.set_current - self.intersect

    def removed(self):
        return self.set_past - self.intersect

    def changed(self):
        return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])

    def unchanged(self):
        return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])

A github gist for this is also available.