Arbazz Hussain
Arbazz Hussain

Reputation: 1932

effecient way to compare 2 dictionaries which has values as list elements to find what is added/removed


def DictChecker(old_dict,new_dict):
    final_added = {}
    final_removed = {}

    for k,v in new_dict.items():
        if k not in old_dict.keys():
            old_dict[k] = v 
            final_added[k] = v 

    for k,v in old_dict.items():
        if  old_dict.keys() != new_dict.keys():
            if k not in new_dict.keys():
                final_removed[k] = v

    for i,j in new_dict.items():
        old_dict_values = old_dict.get(i)
        if (j == old_dict_values):
            break
        else:
            added = list(sorted(set(j) - set(old_dict_values)))
            removed = list(sorted(set(old_dict_values) - set(j)))
            final_added[i] = added
            final_removed[i] = removed

    return final_added,final_removed
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]}

Upvotes: 0

Views: 39

Answers (1)

Orikle
Orikle

Reputation: 46

I would have sent a comment if I could. basically I believe that the sorting part is the time-consuming part. the code below is simply removing occurring values from listed values in each other. have'nt tried it on a large database though.

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

my point is that you can do it without sorting each list. have a good day, hope you found this helpful.

Upvotes: 1

Related Questions