[Tutor] assigning list to keys

Kent Johnson kent37 at tds.net
Tue Jul 14 13:39:08 CEST 2009


On Tue, Jul 14, 2009 at 2:58 AM, Todd Matsumoto<tmatsumoto at gmx.net> wrote:
> Hello,
>
> The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this:
>
> list = []
> dict = {}
> x = 1
>
> dict['int'] = list.append(x)

I don't know what you mean by "pack a dictionary". A fairly common
requirement is for a dictionary that maps keys to a list of values,
and a way to accumulate the values from a list of key, value pairs
where the keys may repeat.

collections.defaultdict is helpful for this, for example:
In [3]: from collections import defaultdict

In [4]: d = defaultdict(list)

In [5]: pairs = [ ('int', 1), ('float', 2.5), ('int', 3), ('float', 3.14) ]

In [6]: for k, v in pairs:
   ...:     d[k].append(v)

In [7]: d
Out[7]: defaultdict(<type 'list'>, {'int': [1, 3], 'float': [2.5,
3.1400000000000001]})

The value of d[k] will be a list, either an empty list or a previously
created one, so d[k].append() adds a new value to the list.

Kent


More information about the Tutor mailing list