Created
April 24, 2014 20:40
-
-
Save merwok/11268759 to your computer and use it in GitHub Desktop.
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
import collections | |
class OrderedDefaultDict(collections.OrderedDict, collections.defaultdict): | |
pass | |
odd = OrderedDefaultDict() | |
odd.default_factory = list | |
odd['a'].append(True) | |
odd['b'].append(False) | |
odd['c'].append(False) | |
print(odd.items()) | |
print(odd['d']) |
You could also only subclass OrderedDict and define a __missing__
method to to the same thing as default_factory in defaultdict.
FTR collections.Counter can also help depending on your need, and it combines well with collections.OrderedDict: http://rhettinger.wordpress.com/2011/05/26/super-considered-super/
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I make defaultdict the first base, then the setitems will fail because the dict has no
__root
(Python 2) or__map
(3) attribute. This is certainly due to defaultdict not callingsuper(...).__init__
. This can be worked around by definingOrderedDefaultDict.__init__(default_factory, items)
and calling the superclasses’__init__
methods explicitly.If OrderedDict is the first base, then the signature of
__init__
has no argument for default_factory, so I had to set it manually after creating my instance.