Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update dictionary items with a for loop

Tags:

python

I would like update a dictionary items in a for loop here is what I have:

>>> d = {}
>>> for i in range(0,5):
...      d.update({"result": i})
>>> d
{'result': 4}

But I want d to have following items:

{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
like image 972
PHA Avatar asked Dec 20 '22 02:12

PHA


2 Answers

As mentioned, the whole idea of dictionaries is that they have unique keys. What you can do is have 'result' as the key and a list as the value, then keep appending to the list.

>>> d = {}
>>> for i in range(0,5):
...      d.setdefault('result', [])
...      d['result'].append(i)
>>> d
{'result': [0, 1, 2, 3, 4]}
like image 114
DeepSpace Avatar answered Feb 02 '23 08:02

DeepSpace


Keys have to be unique in a dictionnary, so what you are trying to achieve is not possible. When you assign another item with the same key, you simply override the previous entry, hence the result you see.

Maybe this would be useful to you?

>>> d = {}
>>> for i in range(3):
...      d['result_' + str(i)] = i
>>> d
{'result_0': 0, 'result_1': 1, 'result_2': 2}

You can modify this to fit your needs.

like image 30
DevShark Avatar answered Feb 02 '23 08:02

DevShark