在Python中使用字典
我试图从excel表格中读取数据,并在循环中形成一个字典,如下所示在Python中使用字典,python,dictionary,for-loop,Python,Dictionary,For Loop,我试图从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
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有两行我正在读取的数据,我的字典值总是被第二行的值覆盖,总是尝试以下方法:
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})
(创建字典)如果这是代码的一部分,我认为每次运行循环时都会创建字典,因此您应该在运行循环之前创建字典,然后更新它,而不是使用
MyDataDictionary.update
,您可以执行MyDataDictionary[dict_key]=temp_list
,这将添加新密钥。如果您使用列作为键名,那么您的数据当然会被覆盖,因为它具有相同的键名。当我初始化temp_list=[]而不是使用temp_list.clear()时,代码开始工作。早些时候,每当我调用temp_list.clear()时,我的字典都会更新为空白。“创建字典”只是一个注释,字典是在循环之前初始化的。当我将temp_list初始化方法从temp_list.clear()更改为temp_list=[]时,代码开始工作。试图找出这两个选项之间的区别。