Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1278
眼角桃花
眼角桃花 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

    If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.

    import unittest
    
    test = unittest.TestCase()
    test.assertEqual(dictA, dictB)
    
    0 讨论(0)
  • 2020-11-27 10:05

    You can use set operations on the keys:

    diff = set(dictb.keys()) - set(dicta.keys())
    

    Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.

    class DictDiffer(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, current_dict, past_dict):
            self.current_dict, self.past_dict = current_dict, past_dict
            self.set_current, self.set_past = set(current_dict.keys()), set(past_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])
    

    Here is some sample output:

    >>> a = {'a': 1, 'b': 1, 'c': 0}
    >>> b = {'a': 1, 'b': 2, 'd': 0}
    >>> d = DictDiffer(b, a)
    >>> print "Added:", d.added()
    Added: set(['d'])
    >>> print "Removed:", d.removed()
    Removed: set(['c'])
    >>> print "Changed:", d.changed()
    Changed: set(['b'])
    >>> print "Unchanged:", d.unchanged()
    Unchanged: set(['a'])
    

    Available as a github repo: https://github.com/hughdbrown/dictdiffer

    0 讨论(0)
  • 2020-11-27 10:06

    Based on ghostdog74's answer,

    dicta = {"a":1,"d":2}
    dictb = {"a":5,"d":2}
    
    for value in dicta.values():
        if not value in dictb.values():
            print value
    

    will print differ value of dicta

    0 讨论(0)
提交回复
热议问题