Search code examples
pythondictionarysubtraction

Python: Getting the difference between two dictionaries


I'm trying to find a way to get the difference between 2 dictionaries, comparing the same keys and the values. That is the word and occurrences.

Say I have two dictionaries:

Dict_1 = {' Chicago ': 3, ' Washington ': 5, ' LA ': 22, ' Boston ': 8, ' Seattle ': 0}
Dict_2 = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

So what I after is the difference of occurrences, showing the differences in the two dictionaries.

[3-4, 5-9, 22-26, 8-12, 0-2] or like this [-1, -4, -4, -4, -2]

I then use those differences for calculations. I'm not very experienced with using dictionaries so any help is appreciated.

I may also have to account for one dictionary not having the same keys. E.G.

Dict_1 = {' Chicago ': 3, ' Washington ': 5, ' LA ': 22, ' Boston ': 8, ' Seattle ': 0, ' Detroit ': 3}
Dict_2 = {' Chicago ': 4, ' Washington ': 9, ' LA ': 26, ' Boston ': 12, ' Seattle ': 2}

Dictionary 1 has Detroit, an entry that dictionary 2 doesn't have. I still want to get the difference, which is going to be 3, as Dict 2 has 0 occurrences of Detroit.


Solution

  • You can use a dictionary comprehension for that:

    diffdict = {
        key: Dict_1.get(key, 0) - Dict_2.get(key, 0)
        for key in Dict_1.keys() | Dict_2.keys()
    }
    

    Here I'm using a default value of zero for the missing keys for both dictionaries, meaning if a value isn't available in Dict_1, but it is in Dict_2, its value will be -Dict_2[key]

    The resulting diffdict will look like this:

    >>> diffdict
    {' Boston ': -4, ' Washington ': -4, ' LA ': -4, ' Chicago ': -1, ' Seattle ': -2}