Reputation: 15204
I am trying to subclass dict
to modify its update
method.
The behavior I am looking for is to add the values of common keys and keep the unique ones.
g1 = MyDict({1: 1, 2: 2})
g2 = MyDict({1: 1, 3: 3})
g1.update(g2) # should result in g1 = {1: 2, 2: 2, 3: 3}
# ^ because it is 1 from g1 + 1 from g2
in other words, as if I was doing:
from collections import Counter
g1 = dict(Counter(g1) + Counter(g2))
For this task, I wrote the following:
class MyDict(dict):
def __update__(self, d2):
keys = set(self).union(d2)
self = {k: self.get(k, 0) + d2.get(k, 0) for k in keys}
return
but when doing:
g1 = MyDict({1: 1, 2: 2})
g2 = MyDict({1: 1, 3: 3})
g1.update(g2)
it produces:
{1: 1, 2: 2, 3: 3}
However, if I do:
class MyDict(dict):
def __add__(self, d2):
keys = set(self).union(d2)
return {k: self.get(k, 0) + d2.get(k, 0) for k in keys}
and then
g1 = g1 + g2
the desired behavior is implemented..
What am I doing wrong when overwriting the update
method?
Upvotes: 2
Views: 73
Reputation: 15204
I found the following way to do it:
class MyDict(dict):
def update(self, d2):
for k in set(self).union(d2):
self[k] = self.get(k, 0) + d2.get(k, 0)
return
which indeed, when doing:
g1 = MyDict({1: 1, 2: 2})
g2 = MyDict({1: 1, 3: 3})
g1.update(g2)
results in:
print(g1) # -> {1: 2, 2: 2, 3: 3}
If there is a better way, let me know.
Thanks for the comments!
Upvotes: 3