I want to make a dictionary like this di = {1: 2, 1: 3, 2: 4, 2: 5, 3: 13, 3:14}
. Here key 1
has multiple values and I want this dictionary di but after adding key and value I am getting di = {1: 3, 2: 5, 3:14}
. Is there any way to achieve duplicate key value dictionary. This is not a homework.
Asked
Active
Viewed 726 times
1

livikmap99
- 31
- 2
-
perhaps you want di to be a list `di = [{1:2}, {1:3}, {2:4}, .... ]` or perhaps each key in the dict should point to a list `di = {1: [2,3], 2:[4,5], .....}`. You cannot repeat a key in a dict though – JonSG May 14 '21 at 19:46
-
1The short answer is that you cannot have duplicate keys in a Python dictionary. What it looks like you are trying to do is a [multimap](https://en.wikipedia.org/wiki/Multimap). You can replicate it by building something on your own. Check [this](https://stackoverflow.com/questions/1731971/is-there-a-multimap-implementation-in-python) answer. It is also possible that there might be another solution entirely that can be used to try to solve your problem. What is the actual problem you are trying to solve that requires this type of implementation? – idjaw May 14 '21 at 19:49
-
Any specific reason you want to have multiple values associated to a single key ? `dict`s are key-value pairs so it's impossible to have 2 identical keys. – fixatd May 14 '21 at 19:59
1 Answers
0
Dictionaries cannot have duplicate keys. If you're trying to associate multiple values with a single key, this can be accomplished by using an iterable to hold values (such as a list or set).
di = {1: (2,3), 2: (4,5), 3: (13,14)}

Andy
- 3,132
- 4
- 36
- 68
-
Can't we split it like this di ={ 1:2,1:3 , 2:4, 2:5 ,3:13, 3:14 } using default dict ? – Akash nitter May 14 '21 at 19:45
-
@Akashnitter defaultdict provides a method for adding a value to a key that doesn't exist yet, not for duplicating keys. – Andy May 14 '21 at 19:48
-
No, as @Oso states. `dict` cannot have duplicate keys so whatever a `collections.defaultdict` might do for us, it is not allowing repeated keys. Though it certainly might make appending to the value of the key easier :-) – JonSG May 14 '21 at 19:48
-