首页 > 代码库 > python获取两个dict的不同
python获取两个dict的不同
参数: dict1, dict2
需求:如果dict1和dict2中有不同的key,那么返回这个(key, dict1[key]);如果dict1和dict2中有相同的key,但是value不同,返回这个(key, dict1[key])
实现:
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。