参数: 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