将旧字典列表与新字典列表进行比较,以发现所有列表对象的键和值之间的差异

问题描述 投票:0回答:1

[StackOverflow上有大量关于直接old dictnew 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_dictnew_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


python dictionary parameter-passing
1个回答
1
投票
由于'name'字段相等时每个字典都被认为是相等的,因此您可以对这些旧名称建立索引,然后在对新条目进行一次迭代后跟踪更新,添加和删除的]]

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

© www.soinside.com 2019 - 2024. All rights reserved.