Python 比较两个以值作为列表元素的字典以查找添加/删除内容的有效方法 下面是当前的方法,但在大型数据集上速度较慢,我正在寻找一种更高效、更快的方法 正在尝试样本数据
如果可以的话,我会发评论的。基本上,我认为排序部分是耗时的部分。下面的代码只是从彼此列出的值中删除出现的值。不过我还没有在大型数据库上尝试过Python 比较两个以值作为列表元素的字典以查找添加/删除内容的有效方法 下面是当前的方法,但在大型数据集上速度较慢,我正在寻找一种更高效、更快的方法 正在尝试样本数据,python,python-3.x,list,python-2.7,Python,Python 3.x,List,Python 2.7,如果可以的话,我会发评论的。基本上,我认为排序部分是耗时的部分。下面的代码只是从彼此列出的值中删除出现的值。不过我还没有在大型数据库上尝试过 from copy import deepcopy def dictionary_union(new, current): newer = deepcopy(new) for new_key, new_list_value in new.items(): if new_key in current: for current_val
from copy import deepcopy
def dictionary_union(new, current):
newer = deepcopy(new)
for new_key, new_list_value in new.items():
if new_key in current:
for current_value in current[new_key]:
if current_value in new_list_value:
new[new_key].remove(current_value)
for added_key, added_list_value in current.items():
if added_key in newer:
for new_value in newer[added_key]:
if new_value in added_list_value:
current[added_key].remove(new_value)
return new, current
我的观点是,您可以不必对每个列表进行排序就可以做到这一点。
祝您愉快,希望这对您有所帮助。不会返回删除的值。删除了“1”打字错误并添加了deepcopy导入,因为“新”词典已发生变异。
current = {"CNAME":[1,2,3,4],"MX":[2,3,1],"WOOT":[1,2,3,4]}
new = {"CNAME":[5,2,10],"MX":[1,4],"AAA":[100,200]}
added,removed = DictChecker(current,new)
print(added)
>> {'AAA': [100, 200], 'CNAME': [5, 10], 'MX': [4]}
print(removed)
>> {'WOOT': [1, 2, 3, 4], 'CNAME': [1, 3, 4], 'MX': [2, 3]}
from copy import deepcopy
def dictionary_union(new, current):
newer = deepcopy(new)
for new_key, new_list_value in new.items():
if new_key in current:
for current_value in current[new_key]:
if current_value in new_list_value:
new[new_key].remove(current_value)
for added_key, added_list_value in current.items():
if added_key in newer:
for new_value in newer[added_key]:
if new_value in added_list_value:
current[added_key].remove(new_value)
return new, current