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

Monika Jisswel monjissvel at googlemail.com
Fri Aug 1 12:49:00 CEST 2008


2008/8/1 Angela Yang <angelayian at yahoo.com>
>
>
> 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.
>
> Do you have some example how to specify this?
>

You already know this :
Collection1 = []
Collection2 = []
Collection1.append('apprentice1')
Collection1.append('apprentice2')

if you add a MainCollection to the picture which can be coded like this:
MainCollection = {'Collection1':[], 'Collection2':[]}
Adding elements to a Collection is as simple as this interactive
session demonstrates :

Python 2.4.4 (#2, Apr 15 2008, 23:43:20)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>> MainCollection = {'Collection1':[], 'Collection2':[]}
>>> type(MainCollection)
<type 'dict'>
>>> MainCollection['Collection1']
[]
>>> MainCollection['Collection1'].append('aa')
>>> MainCollection['Collection1']
['aa']
>>> MainCollection['Collection1'].append('bb')
>>> MainCollection['Collection1']
['aa', 'bb']


More information about the Tutor mailing list