Skip to content

Commit 26ca139

Browse files
author
y-p
committed
ENH: add OrderedDefaultdict to util.compat
1 parent e264115 commit 26ca139

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

pandas/util/compat.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,3 +475,28 @@ def __and__(self, other):
475475
Counter = _Counter
476476
else:
477477
from collections import OrderedDict, Counter
478+
479+
# http://stackoverflow.com/questions/4126348
480+
# Thanks to @martineau at SO
481+
482+
class OrderedDefaultdict(OrderedDict):
483+
def __init__(self, *args, **kwargs):
484+
newdefault = None
485+
newargs = ()
486+
if args:
487+
newdefault = args[0]
488+
if not (newdefault is None or callable(newdefault)):
489+
raise TypeError('first argument must be callable or None')
490+
newargs = args[1:]
491+
self.default_factory = newdefault
492+
super(self.__class__, self).__init__(*newargs, **kwargs)
493+
494+
def __missing__ (self, key):
495+
if self.default_factory is None:
496+
raise KeyError(key)
497+
self[key] = value = self.default_factory()
498+
return value
499+
500+
def __reduce__(self): # optional, for pickle support
501+
args = self.default_factory if self.default_factory else tuple()
502+
return type(self), args, None, None, self.items()

0 commit comments

Comments
 (0)