Cookbook: Associating multiple values with each key in a dictionary

Michael Gilfix mgilfix at eecs.tufts.edu
Tue Jul 30 13:14:14 EDT 2002


On Tue, Jul 30 @ 17:15, Egbert Bouwman wrote:
> On page 9 of the free chapter 01 of their cookbook
> alex and associates present a way to associate multiple values 
> without duplications to a dictionary:
>     d2 = {}
>     d2.setdefault(key, {})[value] = 1
> This produces nested dictionaries with unique keys,
> however with values that I don't need.
> 
> I prefer a solution with lists, as in the one with duplications allowed:
>     d1 = {}
>     d1.setdefault(key, []).append(value)
>     
> This function creates a multivalued list without duplications:
> 
>     def keyplus(dic,key,value):
>         dic.setdefault(key, [])
>         if value not in dic[key]:
>             dic[key].append(value)
>             
> but now I have a feeling that some one-liner is possible. If not, 
> don't we need then a list method 'append_if_not already-there' ?

  The beauty of using dictionaries is that you can always just do the
'setting' operation, regardless of whether or not the item is in the
dict and still have the result be unique (because it always hashes to
the same value). The problem with the list method is that in order to
keep your list unique, you have to check that the item is not already
in the list, which can be expensive.

  I'm not really sure why you prefer the list method. Is there something
that you can't accomplish with the nested dictionaries? Are you looking
perhaps for some ordering? If so, then you're right, the dict solution
might not be best. However I would suggest using a dict as a look up
mechanism to determine whether the item is in the list already before
the append. The result should be considerably faster.

                    -- Mike




More information about the Python-list mailing list