Skip to content

Instantly share code, notes, and snippets.

@zapman449
Created February 4, 2014 04:56
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 zapman449/8798362 to your computer and use it in GitHub Desktop.
Save zapman449/8798362 to your computer and use it in GitHub Desktop.
DeltaDict A dictionary for tracking the deltas between updates.
#!/usr/bin/python
"""
DeltaDict: A python dictionary for keeping track of the delta between numeric
values.
Insert a number in a key, and you'll get that number back. Next insert a
higher number. Now a get() will return the delta between the numbers.
Useful for monitoring applications where you're presented with a monotomically
increasing counter, but only really care about the deltas.
Future improvement: flag into __init__() to allow absolute value deltas
instead of wrapping around at zero.
"""
import collections
class DeltaDict(collections.MutableMapping) :
def __init__(self, *args, **kwargs):
self.store = dict()
self.delta_store = dict()
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
#return self.store[self.__keytransform__(key)]
return self.delta_store[key]
def __setitem__(self, key, value):
if not self.store.has_key(key) or value < self.store[key] :
self.store[key] = value
self.delta_store[key] = value
else :
curval = self.store[key]
self.delta_store[key] = value - curval
self.store[key] = value
#self.store[key] = value
def __delitem__(self, key):
del self.store[key]
del self.delta_store[key]
def __iter__(self):
return iter(self.delta_store)
def __len__(self):
return len(self.store)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment