有关将直接old dict
与new dict
进行比较的关于StackOverflow的大量问答,
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
答案 0 :(得分:1)
由于当“名称”字段相等时,每个字典都被视为相等,因此您可以对这些旧名称建立索引,然后在对新条目进行一次迭代后跟踪更新,添加和删除< / p>
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
这将为您的虚拟数据提供预期的结果。