Is there a way to preserve duplicate keys in python dictionary [duplicate]
I can think of two simple options, assuming you want to keep using a dictionary.
-
You could map keys to lists of items. A
defaultdict
from thecollections
module makes this easy.>>> import collections >>> data = collections.defaultdict(list) >>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')): ... data[k].append(v) ... >>> data defaultdict(<type 'list'>, {'a': ['b', 'c'], 'b': ['c']})
-
You could use additional data to disambiguate the keys. This could be a timestamp, a unique id number, or something else. This has the advantage of preserving a one-to-one relationship between keys and values, and the disadvantage of making lookup more complex, since you always have to specify an
id
. The example below shows how this might work; whether it's good for you depends on the problem domain:>>> for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')): ... i = 0 ... while (k, i) in data: ... i += 1 ... data[(k, i)] = v ... >>> data {('a', 1): 'c', ('b', 0): 'c', ('a', 0): 'b'}
While I'm not 100% sure, I'm pretty sure the answer is no. That sort of violates the purpose of a dictionary in python. How about you change the value to lists so instead of
{Key:value}
you have
{Key:[Value1,value2]}
An alternative to the defaultdict
might be
d = {}
d.setdefault(newkey, []).append(newvalue)
This does the same: append newvalue
to a list which is either already in the dictionary at the given newkey
, or if not, will be put there.