推送字典通过for循环列出

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了推送字典通过for循环列出相关的知识,希望对你有一定的参考价值。

我想通过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}]
答案
   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) 
另一答案

在第二次迭代期间,.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]
另一答案

有什么理由我们不只是使用更简单的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) 

另一答案

你需要做点什么

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)

以上是关于推送字典通过for循环列出的主要内容,如果未能解决你的问题,请参考以下文章

Python - 尝试通过 for 循环创建字典

如何通过带有for循环的字典(python)设置实例的属性

如何使用引导程序和 for 循环在 django 中创建电影片段?

python中的while循环与for循环怎么样那个比较好用?

HTTP/2:stream.end 使用 For-Loop

c_cpp 这个简单的代码片段显示了如何使用有符号整数在C中完成插值。 for()循环确定要插入的范围