d={}
for i in range (5):
d['key']=i
lst.append(d)
print(lst)
>>>[{'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}]
Why i didn't got this result plz :>>>[{'key': 0}, {'key': 1}, {'key': 2}, {'key': 3}, {'key': 4}]
?
CodePudding user response:
This code will work:
lst = []
for i in range(1, 6):
lst.append({"key", i})
print(lst)
The problem was that you are appending the variable d
to lst
. the value of lst
is now [d, d, d, d, d]
. When printing, this evaluates to d
's current value, which happens to be {'key', 4}
. My code appends the value of d to the list without creating d
. This is at least my interpretation of this. Could be wrong.