Created
August 10, 2018 12:44
-
-
Save spacelis/bbfde912e80678d7722e9d15b2dbb733 to your computer and use it in GitHub Desktop.
A Dict class that can merge keys by applying function to the values associated with the keys to merge.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MergeDict(dict): | |
def __init__(self, *args, **kwargs): | |
super(MergeDict, self).__init__(*args, **kwargs) | |
self.key_parent = {} | |
self.key_val = {} | |
def find_rep(self, k): | |
orig_k = k | |
if k in self.key_parent: | |
while k != self.key_parent[k]: | |
k = self.key_parent[k] | |
self.key_parent[orig_k] = k | |
return k | |
def merge_keys(self, k, l, merge_func=lambda k, l: k): | |
k = self.find_rep(k) | |
l = self.find_rep(l) | |
self.key_parent[l] = k | |
self[k] = merge_func(self[k], self[l]) | |
del self[l] | |
return k | |
def norm_val(self, k): | |
return self[self.find_rep(k)] | |
md = MergeDict(a=1, b=2, c=3, d=4, e=5) | |
md.merge_keys('a', 'b', lambda acc, v: acc + v) | |
assert md.norm_val('b') == 3 | |
assert md.norm_val('a') == 3 | |
assert 'a' in md | |
assert 'b' not in md |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment