通过for循环将字典推送到列表

时间:2019-04-14 14:34:08

标签: python django list dictionary django-rest-framework

我想通过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}]

预期的打印输出(结果):

[{Dictionary 1}, {Dictionary 2}]

4 个答案:

答案 0 :(得分:0)

   results = []
   for i in range(count): #->Count is 2, 2 different dictionaries
      result = {
            '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) 
      results.append(result) 

   print(results) 

答案 1 :(得分:0)

在第二次迭代期间,.update方法将更新列表中的第一个字典。这是因为这两个字典指向相同的引用。

一个类似的例子是:

a = [1, 2, 3]
b = a
a[0] = 'this value is changed in b as well'
print(b)
#['this value is changed in b as well', 2, 3]

答案 2 :(得分:0)

我们是否有理由不只是使用更简单的import openpyxl filename = "example.xlsx" wb = openpyxl.load_workbook(filename) sheet = wb['Sheet1'] status = sheet['A1'].value print(status) sheet.delete_rows(0, 1) wb.save(filename) 循环?

for

答案 3 :(得分:0)

您需要做类似的事情

results = []
for x in api_results: 
    result = {
        'workitem_id': str(x['workitem_id']),
        'workitem_header': x['workitem_header'],
        'workitem_desc': x['workitem_desc'],
        'workitem_duration': str(x['workitem_duration'])
    }
    results.append(result) 

print(results)