Cookbook: Associating multiple values with each key in a dictionary
Egbert Bouwman
egbert at bork.demon.nl
Tue Jul 30 11:15:37 EDT 2002
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' ?
--
Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991
========================================================================
More information about the Python-list
mailing list