【问题标题】:Using Dictionary in Python在 Python 中使用字典
【发布时间】:2020-01-23 11:19:23
【问题描述】:

我正在尝试从 Excel 工作表中读取数据并在循环中形成字典,如下所示。

for row in range(2,sheet.max_row+1):
    temp_list.clear()
    for col in range (2,sheet.max_column):
        temp_list.append(sheet.cell(row,col).value)    
    dict_key = sheet.cell(row,1).value
Create a dictionary
   MyDataDictionary.update( {dict_key : temp_list})

假设我的 excel 有两行正在读取的数据,我的字典值总是被第二行的值覆盖

【问题讨论】:

  • 不要使用MyDataDictionary.update,你可以使用MyDataDictionary[dict_key] = temp_list,这将添加新的密钥。如果您使用列作为键名,那么您的数据当然会被覆盖,因为它具有相同的键名。

标签: python dictionary for-loop


【解决方案1】:

(创建字典)如果这是您的代码的一部分,我认为每次运行循环时都会创建您的字典,因此您应该在运行循环之前创建字典然后更新它

【讨论】:

  • “创建字典”仅作为注释,字典在循环之前被初始化。当我将 temp_list 初始化方法从 temp_list.clear() 更改为 temp_list =[] 时,代码开始工作。试图找出这两个选项之间的区别。
【解决方案2】:

试试下面的方法:

if MyDataDictionary.get(dict_key, []):
    #updates the existing key assuming that temp_list is always a list
    MyDataDictionary.get(dict_key).extend(temp_list)
else:
    #creates a new key
    MyDataDictionary.update({dict_key : temp_list})

【讨论】:

  • 当我初始化 temp_list=[] 而不是使用 temp_list.clear() 时,代码开始工作。之前,每次我调用 temp_list.clear() 时,我的字典都会更新为空白。
猜你喜欢
  • 1970-01-01
  • 2016-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2017-10-26
相关资源
最近更新 更多