How to get the difference between two dictionaries in Python?

前端 未结 9 1357
庸人自扰
庸人自扰 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:25

    You were right to look at using a set, we just need to dig in a little deeper to get your method to work.

    First, the example code:

    test_1 = {"foo": "bar", "FOO": "BAR"}
    test_2 = {"foo": "bar", "f00": "b@r"}
    

    We can see right now that both dictionaries contain a similar key/value pair:

    {"foo": "bar", ...}
    

    Each dictionary also contains a completely different key value pair. But how do we detect the difference? Dictionaries don't support that. Instead, you'll want to use a set.

    Here is how to turn each dictionary into a set we can use:

    set_1 = set(test_1.items())
    set_2 = set(test_2.items())
    

    This returns a set containing a series of tuples. Each tuple represents one key/value pair from your dictionary.

    Now, to find the difference between set_1 and set_2:

    print set_1 - set_2
    >>> {('FOO', 'BAR')}
    

    Want a dictionary back? Easy, just:

    dict(set_1 - set_2)
    >>> {'FOO': 'BAR'}
    

提交回复
热议问题