Skip to content

Instantly share code, notes, and snippets.

@vartagg vartagg/lazy_dict.py

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.