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.

  1. You could map keys to lists of items. A defaultdict from the collections 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']})
    
  2. 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'}
    

Leave a Comment

deneme bonusu veren sitelerbahis casino