Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of map<int, vector<int> > in Python?

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?

like image 330
Jeroen Dirks Avatar asked Nov 27 '08 21:11

Jeroen Dirks


1 Answers

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])]
like image 200
ddaa Avatar answered Oct 17 '22 03:10

ddaa