[StackOverflow上有大量关于直接old dict
与new dict
进行比较的问答,
old_dict = [{'name':'john','age':10},{'name':'cena','age':26},{'name':'tom','age':24}]
new_dict = [{'name':'cena','age':26},{'name':'john','age':13},{'name':'henry','age':32},{'name':'steave','age':50}]
我想将old_dict
和new_dict
作为参数传递给该函数,在该函数中比较键,所有列表对象中的值以及该函数将返回以下字段
return updated_key_val,added_key_val,removed_new_key_val
print(updated_key_val)
>> [{'name':'john','age':13}] ### age value updated from 10 to 13
print(added_key_val)
>> [{'name':'henry','age':32},{'name':'steave','age':50}] ## old results doesn't had this 2 dicts so this are new dicts
print(removed_new_key_val)
>> [{'name':'tom','age':24}] ## this has been removed in newer results
def entries_diff(old_entries, new_entries):
updated, added = [], []
old_index = {e['name']: e for e in old_entries}
for e in new_entries:
name = e['name']
if name not in old_index:
added.append(e)
else:
old = old_index[name]
if old != e:
updated.append(e)
del old_index[name]
removed = list(old_index.values())
return updated, added, removed