Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add element with the same key in dictionary?

I have this code:

import json

dictionary = {}
variable = 0

for i in range(5):
    variable += 1
    dictionary['number'] = variable

print(json.dumps(dictionary))
Output: {"number": 5}

I think my code just changing value in dictionary instead of creating new one.
I want the dictionary look like this:

{"number": 1, "number": 2, "number": 3, "number": 4, "number": 5}

i know that i can do this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"number": [1, 2, 3, 4, 5]}

but i want to do like i said before. I just want json with the same keys and different variables so if there is another option to achieve my goal, then tell me.

>Solution :

This isn’t possible with Python dictionaries. Python will always overwrite a key if you try to use it more than once.

You could try a list of single key-value dicts to get close:

[{"number": 1}, {"number": 2}, {"number": 3}, {"number": 4}, {"number": 5}]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading