【问题标题】:Push dictionary to list via for loop通过 for 循环将字典推送到列表
【发布时间】: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


【解决方案1】:
   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) 

【讨论】:

  • 愚蠢的我。谢谢 :)
【解决方案2】:

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

【讨论】:

    【解决方案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) 
    
    

    【讨论】:

      【解决方案4】:

      你需要做类似的事情

      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)
      

      【讨论】:

        猜你喜欢
        • 2021-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-20
        • 2016-02-26
        相关资源
        最近更新 更多