首页 > 编程语言 > 详细

python获取两个dict的不同

时间:2014-05-28 21:09:13      阅读:485      评论:0      收藏:0      [点我收藏+]

参数: dict1, dict2

需求:如果dict1和dict2中有不同的key,那么返回这个(key, dict1[key]);如果dict1和dict2中有相同的key,但是value不同,返回这个(key, dict1[key])

实现:

bubuko.com,布布扣
def dict_different_data(first, second):
    """
    get the different data bewtten two dicts objects
    return :result = first - second

    """
    assert isinstance(first, dict)
    assert isinstance(second, dict)
    different_data = {}
    update_key = set(first).intersection(set(second))
    insert_key = set(first).difference(set(second))
    delet_key =  set(second).difference(set(first))

    #updata data item which are both on first and second  and Not equal values
    for k in update_key:
        if(isinstance(first[k], dict)):
            result = dict_different_data(first[k], second[k])
            if len(result) > 0:
                different_data[k] = result
        elif first[k] != second[k]:
            different_data[k] = first[k]        
    #insert new item from first
    for k in insert_key:
        different_data[k] = first[k]
    #delet data 
    for k in delet_key :
        different_data[k] = None        

    return different_data

if __name__ == "__main__":
    dic1 = {
        name: test,
        score: 89
    }
    dic2 = {
        name: test,
        score: 29,
        age: 23
    }
    result = dict_different_data(dic2, dic1)
    print result
bubuko.com,布布扣

 

python获取两个dict的不同,布布扣,bubuko.com

python获取两个dict的不同

原文:http://www.cnblogs.com/xiami303/p/3754789.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!