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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM