Home > OS >  How to add element with the same key in dictionary?
How to add element with the same key in dictionary?

Time:08-02

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:

{"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.

CodePudding user response:

You can't have multiple of the same key but you can have a list of multiple values for the one key:

import json

dictionary = {}
variable = 0
dictionary['number'] = []


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

print(json.dumps(dictionary))

CodePudding user response:

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}]

  • Related