Skip to content

Instantly share code, notes, and snippets.

@rlkelly
Created October 21, 2016 17:15
Show Gist options
  • Save rlkelly/da88ec58008db8fa94a5259dc9713d72 to your computer and use it in GitHub Desktop.
Save rlkelly/da88ec58008db8fa94a5259dc9713d72 to your computer and use it in GitHub Desktop.
class DefaultDict(dict):
def __new__(cls, default_value):
new_instance = super(DefaultDict, cls).__new__(cls, default_value)
return new_instance
def __init__(self, default_value):
self.default_value = default_value
super(DefaultDict, self).__init__()
def __getitem__(self, item):
if item not in self:
self[item] = self.default_value
return self.default_value
def __repr__(self):
return 'DefaultDict <default %s> %s' % (self.default_value, dict.__repr__(self))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment