I am looking for the best way to create a list in python that creates hashed indexes (dicts) for all the properties of the objects put into the list.
>>> foo = IndexingList([{ 'id': 1, 'name': 'cat' }, { 'id': 2, 'name': 'dog' }])
>>> foo[0]
{'id': 1, 'name': 'cat'}
>>> foo.findall('id', 2)
[{'id': 2, 'name': 'dog'}]
>>> foo += {'id': 3, 'name': 'dog'}
>>> foo.findall('name', 'dog')
[{'id': 2, 'name': 'dog'}, {'id': 3, 'name': 'dog'}]
I imagine the data structure of the IndexingList would then look like this:
{
'items': [
{ 'id': 1, 'name': 'cat' },
{ 'id': 2, 'name': 'dog' }
],
'indexes': {
'id': {
1: [{ 'id': 1, 'name': 'cat' }],
2: [{ 'id': 2, 'name': 'dog' }]
},
'name': {
'cat': [{ 'id': 1, 'name': 'cat' }],
'dog': [
{ 'id': 2, 'name': 'dog' },
{ 'id': 3, 'name': 'dog' }
]
}
}
}
where the objects within the ‘indexes’ nodes refer to the same objects in ‘items’.
I think property values that are themselves objects could receive unique index-keys by using str(property) to obtain something to stick in ‘indexes’.
This is actually pretty easy to do using some
collections.defaultdict()s – although you might consider using an actual database if you are using this a lot.Used like so: