I'm comparing two OrderedDict
objects and I need to find added keys, removed keys, and keys that are present in both (the intersection). Sets are designed for exactly that sort of thing, so my initial attempt involved getting the keys, converting to sets and then comparing/intersecting appropriately. The trouble I ran into is that I need the order of the original keys to be preserved all the way through the process (hence the use of OrderedDict
) and sets don't seem to do that. I did some googling about ordered sets in python3, but there don't appear to be any native solutions, and I don't really want to bring in another class/library for this one small computation. Instead, I came up with these lines of code:
def differences(a, b):
added = []
removed = []
overlap = []
for key in a.keys():
if key in b:
overlap.append(key)
else:
removed.append(key)
for key in b.keys():
if not key in a:
added.append(key)
return (added, removed, overlap)
I'm especially interested in hearing suggestions on different ways of tackling this problem, but I'm happy to hear any general suggestions.
{'a': True, 'b': False}
and{'b': False, 'a': True}
unchanged? If so, in which order should the keys occur inoverlap
?['a', 'b']
or['b', 'a']
? \$\endgroup\$