叽叽喳喳,嘻嘻哈哈

导航

两个字典增量部分


def get_increment_between_two_dict(item_old, item_new):
    """
    比较两个字典,并返回增量部分
    :param dict_old = {"a":{"a_1":"haha","a_2":[1,2,3],"a_3":10},"b":{"b_1":"an","b_2":10},
                        'd':{"d_1":[1,2,3],"d_2":(7,8), "d_3":{"a","b"}}}

    :param dict_new =  {"a":{"a_1":"hehe","a_2":[1,2,3],"a_3":30},"b":{"b_1":"an","b_2":10},
                    "c":{"c_1":{"c_1_1":"3"},"c_2":10},'d':{"d_1":[1,2,3,4],"d_2":(8, 9),"d_3":{"a","b","c"}}}

    :return: {"a":{"a_1":"hehe","a_3":30},"c":{"c_1":{"c_1_1":"3"},"c_2":10}, 'd':['d_1':[4], 'd_2':(9,),'d_3':{'c'}}
    """

    if isinstance(item_old, dict) and isinstance(item_new, dict):
        increment_dict = {}
        for key in item_new:
            if key not in item_old:
                increment_dict[key] = item_new[key]
            else:
                result = get_increment_between_two_dict(item_old[key], item_new[key])
                if result:
                    increment_dict[key] = result
        return increment_dict

    else:
        if isinstance(item_old, list) and isinstance(item_new, list):
            return list(set(item_new) - set(item_old))
        elif isinstance(item_old, tuple) and isinstance(item_new, tuple):
            return tuple(set(item_new) - set(item_old))
        elif isinstance(item_old, set) and isinstance(item_new, set):
            return item_new - item_old
        elif item_old != item_new:
            return item_new
        return None

posted on 2019-07-10 14:42  叽叽喳喳,嘻嘻哈哈  阅读(150)  评论(0编辑  收藏  举报