newbie555 newbie555 - 22 days ago 5
Python Question

Is there a way to preserve duplicate keys in python dictionary

is there any way to store duplicate keys in a dictionary?

I have a specific requirement to form pairs of requests and responses.

Requests from a particular node to another particular node form same keys. I need to store both those.

But if I tried to add them to dictionary, first one is being replaced by second. Is there any way?

Answer

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'}