Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1435
眼角桃花
眼角桃花 2020-11-27 09:33

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not

21条回答
  •  日久生厌
    2020-11-27 10:04

    As mentioned in other answers, unittest produces some nice output for comparing dicts, but in this example we don't want to have to build a whole test first.

    Scraping the unittest source, it looks like you can get a fair solution with just this:

    import difflib
    import pprint
    
    def diff_dicts(a, b):
        if a == b:
            return ''
        return '\n'.join(
            difflib.ndiff(pprint.pformat(a, width=30).splitlines(),
                          pprint.pformat(b, width=30).splitlines())
        )
    

    so

    dictA = dict(zip(range(7), map(ord, 'python')))
    dictB = {0: 112, 1: 'spam', 2: [1,2,3], 3: 104, 4: 111}
    print diff_dicts(dictA, dictB)
    

    Results in:

    {0: 112,
    -  1: 121,
    -  2: 116,
    +  1: 'spam',
    +  2: [1, 2, 3],
       3: 104,
    -  4: 111,
    ?        ^
    
    +  4: 111}
    ?        ^
    
    -  5: 110}
    

    Where:

    • '-' indicates key/values in the first but not second dict
    • '+' indicates key/values in the second but not the first dict

    Like in unittest, the only caveat is that the final mapping can be thought to be a diff, due to the trailing comma/bracket.

提交回复
热议问题