python 获取两个dict的差异

 
 
class DiffDict(object):
    """获取两个dict的差异"""

    def __init__(self, current, last):
        self.current = current
        self.last = last
        self.set_current = set(current)
        self.set_last = set(last)
        self.intersect_keys = self.set_current & self.set_last

    def get_added(self):
        """current - 交集 = 新增的key"""
        added_keys = self.set_current - self.intersect_keys
        return [{'key': key, 'value': self.current.get(key)} for key in added_keys]

    def get_removed(self):
        """last - 交集 = 减去的key"""
        removed_keys = self.set_last - self.intersect_keys
        return [{'key': key, 'value': self.current.get(key)} for key in removed_keys]

    def get_changed(self):
        """用交集中的key去两个dict中找出值不相等的"""
        changed_keys = set(o for o in self.intersect_keys if self.current.get(o) != self.last.get(o))
        return [{
            'key': key,
            'value': '%s -> %s' % (self.last.get(key), self.current.get(key))
        } for key in changed_keys]
posted @ 2018-11-02 14:44  朔雪寒D.A.G  阅读(1733)  评论(0编辑  收藏  举报