Skip to content

Instantly share code, notes, and snippets.

@vartagg
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vartagg/48f7fed70a480409631d to your computer and use it in GitHub Desktop.
Save vartagg/48f7fed70a480409631d to your computer and use it in GitHub Desktop.
from copy import copy
class LazyDict(dict):
"""
A dict class with default value for unfound keys
>>> ldict = LazyDict(0)
>>> ldict
{}
>>> ldict['x'] += 1
>>> ldict
{'x': 1}
>>> ldict['x'] += 1
>>> ldict
{'x': 2}
>>> ldict['y'] += 10
>>> ldict == {'x': 2, 'y': 10}
True
>>> ldict['z'] == 0
True
>>> ldict == {'x': 2, 'y': 10, 'z': 0}
True
>>> ldict = LazyDict([])
>>> ldict
{}
>>> ldict['a'].append(20)
>>> ldict['a'].append(20)
>>> ldict
{'a': [20, 20]}
>>> ldict['b'].append(6)
>>> ldict == {'a': [20, 20], 'b': [6]}
True
"""
def __init__(self, default_value):
super(LazyDict, self).__init__()
self._default_value = default_value
def __getitem__(self, item):
if not item in self:
self.__setitem__(item, copy(self._default_value))
return super(LazyDict, self).__getitem__(item)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment