I've written a utility class BetterDict
to help me on some of my other projects. I've implemented the &
, +
, and -
operators. It extends from the base class dict
so I can use all the builtin functions without having to rewrite them all. I would like some feedback on my implementation, best practices, more pythonic way of doing this, etc.
from typing import NewType
BetterDict = NewType('BetterDict', object)
class BetterDict(dict):
def __and__(self, other: BetterDict) -> BetterDict:
"""
Returns a dictionary containing only the keys that are
present in both dicts.
"""
result = BetterDict()
for (sk, _), (ok, ov) in zip(self.items(), other.items()):
if sk == ok:
result[sk] = ov
return result
def __add__(self, other: BetterDict) -> BetterDict:
"""
Combines two dictionaries, replacing same keys with "other" values.
"""
result = BetterDict()
for k, v in self.items():
result[k] = v
for k, v in other.items():
result[k] = v
return result
def __sub__(self, other: BetterDict) -> BetterDict:
"""
Returns a dictionary containing only the keys that are not
present in both dicts.
"""
result = BetterDict()
keys = list(set(self.keys()).symmetric_difference(other.keys()))
for key in keys:
if key in self.keys():
result[key] = self[key]
if key in other.keys():
result[key] = other[key]
return result
Example Code
from better_dict import BetterDict
a = BetterDict({'a': 1})
b = BetterDict({'a': 3, 'b': 2})
print(a & b)
print(a + b)
print(a - b)
__and__()
does not work as claimed. For example,print(BetterDict({'z': 3, 'a': 2, 'b': 1}) & BetterDict({'a': 3, 'b': 2}))
produces an empty dict. You need to figure out which keys exist in both dicts, not simply assume that items from each dict are stored in the same order (chances are, they are not). \$\endgroup\$