[Tutor] how do I create a lists of values associated with a key?

Kent Johnson kent37 at tds.net
Fri Aug 1 12:45:53 CEST 2008


On Thu, Jul 31, 2008 at 11:16 PM, Angela Yang <angelayian at yahoo.com> wrote:
> Hi,
>
> I have a list of values for one key.  How do I specify this data structure?
>
> First tried,
>
> collection = []
> collection['abby'].append('apprentice1')
> collection['abby'].append('apprentice2')
>
> That did not work because list index is not numeric.
> But for dictionaries, it is key - value pairs.  But I need key -> multiple
> values.

A dict or defaultdict  with list values would work well here. The
defaultdict has the advantage of not requiring any user code to handle
missing keys:

In [7]: from collections import defaultdict
In [8]: c=defaultdict(list)
In [9]: c['abby'].append('apprentice1')
In [10]: c['abby'].append('apprentice2')
In [11]: c
Out[11]: defaultdict(<type 'list'>, {'abby': ['apprentice1', 'apprentice2']})

Kent


More information about the Tutor mailing list