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?
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 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']})
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With