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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。