Update dictionary items with a for loop

时间:2015-06-26 09:45:06

标签: 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}

5 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

You can't have different values for the same key in your dictionary. One option would be to number the result:

d = {}
for i in range(0,5):
    result = 'result' + str(i)
    d[result] = i
d
>>> {'result0': 0, 'result1': 1, 'result4': 4, 'result2': 2, 'result3': 3}

答案 2 :(得分:1)

PHA in dictionary the key cant be same :p in your example

{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}

you can use list of multiplw dict:

[{},{},{},{}]

答案 3 :(得分:0)

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 sinply 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.

答案 4 :(得分:0)

>>> d = {"result": []}
>>> for i in range(0,5):
...     d["result"].append(i)
...    
>>> d
{'result': [0, 1, 2, 3, 4]}