Dare to say "dick measuring contest" on this site and you get a warning for supposedly offending someone who doesn't have one? lol. Goes to show the snowflakeness of this site.
I know dicts are ordered by default from 3.7 onwards (so you could just use defaultdict), but I needed to mix the defaultdict and OrderedDict at one point. Introducing the DefaultOrderedDict:
fromcollectionsimportOrderedDictfromcopyimportdeepcopyclassDefaultOrderedDict(OrderedDict):"""Extending getter functions to provide defaults."""_default=dict()def__init__(self,*args,default,**kwargs):self._default=defaultsuper().__init__(*args,**kwargs)def__getitem__(self,key):ifkeyinself:returnself.get(key)value=self[key]=deepcopy(self._default)returnvaluedef__deepcopy__(self,memo):"""Return a deep copy of self."""obj=DefaultOrderedDict(default=self._default)forkey,valueinself.items():obj[key]=deepcopy(value)returnobj
one example of how it can be used:
terms_by_func=DefaultOrderedDict(default=[])
it will basically deepcopy() the contents of the default value.
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
Neat! My first thought was to wonder if it could be done with multiple inheritance between defaultdict and OrderedDict, but that seems like that could be a big nightmare, so your method is probably cleaner. :)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I know dicts are ordered by default from 3.7 onwards (so you could just use
defaultdict
), but I needed to mix thedefaultdict
andOrderedDict
at one point. Introducing theDefaultOrderedDict
:one example of how it can be used:
it will basically
deepcopy()
the contents of the default value.Neat! My first thought was to wonder if it could be done with multiple inheritance between defaultdict and OrderedDict, but that seems like that could be a big nightmare, so your method is probably cleaner. :)