How to get the difference between two dictionaries in Python?

前端 未结 9 1333
庸人自扰
庸人自扰 2020-11-27 04:45

I have two dictionaries. I need to find the difference between the two which should give me both key and value.

I have searched and found some addons/packages like d

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 05:23

    A function using the symmetric difference set operator, as mentioned in other answers, which preserves the origins of the values:

    def diff_dicts(a, b, missing=KeyError):
        """
        Find keys and values which differ from `a` to `b` as a dict.
    
        If a value differs from `a` to `b` then the value in the returned dict will
        be: `(a_value, b_value)`. If either is missing then the token from 
        `missing` will be used instead.
    
        :param a: The from dict
        :param b: The to dict
        :param missing: A token used to indicate the dict did not include this key
        :return: A dict of keys to tuples with the matching value from a and b
        """
        return {
            key: (a.get(key, missing), b.get(key, missing))
            for key in dict(
                set(a.items()) ^ set(b.items())
            ).keys()
        }
    

    Example

    print(diff_dicts({'a': 1, 'b': 1}, {'b': 2, 'c': 2}))
    
    # {'c': (, 2), 'a': (1, ), 'b': (1, 2)}
    

    How this works

    We use the symmetric difference set operator on the tuples generated from taking items. This generates a set of distinct (key, value) tuples from the two dicts.

    We then make a new dict from that to collapse the keys together and iterate over these. These are the only keys that have changed from one dict to the next.

    We then compose a new dict using these keys with a tuple of the values from each dict substituting in our missing token when the key isn't present.

提交回复
热议问题