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

时间:2019-11-22 16:39:15

标签: python dictionary parameter-passing

有关将直接old dictnew 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_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


1 个答案:

答案 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

这将为您的虚拟数据提供预期的结果。