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
defaultdictfrom thecollectionsmodule makes this easy.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: