In C++ often do something like this:
typedef map<int, vector<int> > MyIndexType;
Where I then use it like this:
MyIndexType myIndex;
for( ... some loop ...)
{
myIndex[someId].push_back(someVal);
}
If there was no entry in the map the code will insert a new empty vector and then append to it.
In Python it would look like this:
myIndex = {}
for (someId,someVal) in collection:
try:
myIndex[someId].append(someVal)
except KeyError:
myIndex[someId] = [someVal]
The try except is a bit ugly here. Is there a way to tell the dictionary an object type to insert when a KeyError is encountered at dictionary declaration time?
You want to use:
from collections import defaultdict
myIndex = defaultdict(list)
myIndex[someId].append(someVal)
Standard Library defaultdict
objects.
Example usage from the Python documentation:
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With