推送字典通过for循环列出

问题描述 投票:1回答:4

我想通过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}]
python django list dictionary django-rest-framework
4个回答
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) 

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]

0
投票

有什么理由我们不只是使用更简单的for循环?

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) 


0
投票

你需要做点什么

dictionaries = [  # Let this be the list of dictionaries you have (in your api response?)
    {
        'workitem_id': 1,
        'workitem_header': 'header1',
        'workitem_desc': 'description2',
        'workitem_duration': 'duration2'
    },
    {
        'workitem_id': 2,
        'workitem_header': 'header2',
        'workitem_desc': 'description2',
        'workitem_duration': 'duration2'
    }
]

results = []
for dictionary in dictionaries:
    results.append(dictionary)

print(results)
© www.soinside.com 2019 - 2024. All rights reserved.