Skip to content

Instantly share code, notes, and snippets.

@merwok
Created April 24, 2014 20:40
Show Gist options
  • Save merwok/11268759 to your computer and use it in GitHub Desktop.
Save merwok/11268759 to your computer and use it in GitHub Desktop.
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'])
@merwok
Copy link
Author

merwok commented Apr 24, 2014

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