Cookbook: Associating multiple values with each key in a dictionary

Dave Reed dreed at capital.edu
Tue Jul 30 16:50:53 EDT 2002


> From: Egbert Bouwman <egbert at bork.demon.nl>
> 
> On Tue, Jul 30, 2002 at 01:14:14PM -0400, Michael Gilfix wrote:
> > 
> >   I'm not really sure why you prefer the list method. Is there something
> > that you can't accomplish with the nested dictionaries?
> 
> When I need
>   { 'boys': ['mike', 'egbert'], 'girls': ['laura','lisa'] }
> it hurts me when I have to build:  
>   { 'boys': {'mike' : 1, 'egbert' : 1}, 'girls': {'laura' : 1,'lisa' : 1} }
>   
> That adds an extra layer of complexity when i construct it,
> I have to remember or document that the values can be thrown away,
> and I have now sets of keys, while I need sets of values.
> 
> I try to be a good pythonista, so I and simplicity come first, 
> and efficiency and implementation come second.
> 
> Of course that all changes when I really need the values, ie when
> they don't have some dummy value anymore. But in that case 
> we simply have a nested dictionary, which is not our subject now.
> 
> As an afterthought: is it necessary that lists are slower than
> dictionaries ?  Cannot they be subjected to some hash machine as well ?
> At least in some cases, ie when you search in lists ?
> 
> egbert

The following works:

{ 'boys': ('mike', 'egbert'), 'girls': ('laura','lisa') }

Dave




More information about the Python-list mailing list