【发布时间】:2019-04-14 14:34:07
【问题描述】:
我想通过 for 循环将两个字典推送到一个列表中。我不明白为什么它不起作用。你能帮忙吗? :)
result = {}
results = []
for i in range(count): # Count is 2, 2 different dictionaries
result.update({
'workitem_id': str(api_results[i]['workitem_id']),
'workitem_header': api_results[i]['workitem_header'],
'workitem_desc': api_results[i]['workitem_desc'],
'workitem_duration': str(api_results[i]['workitem_duration'])})
print(result) # Shows the two different dictionaries
results.append(result)
print(results) # Shows the list of two dictionaries, but the list contains the last dictionary for 2 times.
Output print(result): {Dictionary 1} , {Dictionary 2}
Output print(results): [{Dictionary 2} , {Dictionary 2}]
print(results) 的预期输出:
[{Dictionary 1}, {Dictionary 2}]
【问题讨论】:
-
在循环内声明
result = {}。 -
你不断更新same字典。
标签: python django list dictionary django-rest-framework