<p>In C++ often do something like this:</p>

<pre><code>typedef map&lt;int, vector&lt;int&gt; &gt; MyIndexType;
</code></pre>

<p>Where I then use it like this:</p>

<pre><code>MyIndexType myIndex;
for( ... some loop ...)
{
  myIndex[someId].push_back(someVal);
}
</code></pre>

<p>If there was no entry in the map the code will insert a new empty vector and then append to it.</p>

<p>In Python it would look like this:</p>

<pre><code>myIndex = {}

for (someId,someVal) in collection:
   try:
      myIndex[someId].append(someVal)
   except KeyError:
      myIndex[someId] = [someVal]
</code></pre>

<p>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?</p>

Something like this perhaps:
```
```
myIndex = {}
for (someId,someVal) in collection:
    myIndex.setdefault(someId, []).append(someVal)
```
```