Skip to content

Instantly share code, notes, and snippets.

@pezon
Created August 9, 2017 22:15
Show Gist options
  • Save pezon/b2624643b3554eba18bb7d9eca223db6 to your computer and use it in GitHub Desktop.
Save pezon/b2624643b3554eba18bb7d9eca223db6 to your computer and use it in GitHub Desktop.
Collection class
from collections import defaultdict
class Collection(object):
def __init__(self, items={}, id='id'):
self.id = id
self.items = defaultdict(dict)
self.update(items)
def __getitem__(self, key):
return self.items[int(key)]
def __setitem__(self, key, value):
self.items[int(key)].update(value)
def filter(self, predicate):
items = filter(predicate, self.items.values())
return Collection(id=self.id, items=items)
@property
def ids(self):
return self.items.keys()
def update(self, iterable):
for item in iterable:
id = item[self.id]
self.items[id].update(item)
if __name__ == '__main__':
c = Collection()
c.update([{
'id': 1,
'foo': True
}, {
'id': 2,
'foo': False,
'bar': 'okay',
}, {
'id': 4,
'whizz': 'bang'
}])
c.update([{'id': 5, 'cool': 'and the gang'}])
c.update([{'id': 5, 'kool': 'nope'}])
filtered_items = c.filter(lambda i: i.get('foo') == True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment