-2

I have this dictionary:

dictk={"hi":1, "hi":3, "o":7, "o":2, "p":1, "e":5}
for key, val in dictk.items():
    print(key, val)

output:

hi 3
o 2
p 1
e 5

These are not all the pairs in the dictionary, is there a way to get all of them, such that the output will be something like this:

hi 1
hi 3
o 7
o 2
p 1
e 5

Thank you

Volxxe
  • 11
  • 3
  • 1
    Short answer: no! That dict of yours (as any other dict) does **not** have duplicate keys (just because there are duplicates in the dict literal that creates the dict does not alter that fact). – user2390182 Feb 05 '21 at 11:26
  • 1
    Well, a complex answer is for you to turn your dict into a string first, which *might* then be `json` and then get `json` to parse them with a custom hook to get at the duplicates. What you have currently is some python code which will necessarily discard duplicates whilst creating the `dict`. – quamrana Feb 05 '21 at 11:27
  • If that's something you need, change it to list of tuples/lists. – Tom Wojcik Feb 05 '21 at 11:27
  • Please review https://docs.python.org/3/tutorial/datastructures.html#dictionaries – costaparas Feb 05 '21 at 11:29

1 Answers1

1

A dictionary can contain only one instance of a key.

If you print your dictionary object dictk, you will see it has all distinct keys.

dictk={"hi":1, "hi":3, "o":7, "o":2, "p":1, "e":5}
print(dictk)

Output:

{'hi': 3, 'o': 2, 'p': 1, 'e': 5}

You'll need a list of values to have multiple values for a key.

If you have repeated keys then the last value will overwrite other values written previously for that key.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35