将 Excel 的列转换为 python 中的字典

Convert columns of an Excel into dictionary in python

我的 excel 文件中有三列,我必须使用 xlrd 将前两列的所有行转换为字典。

预期输出:

{'Sam' : 'Tester', 'John' : 'Developer', 'Fin' : 'Tester'}

for i in range(1, worksheet.nrows):
    row = worksheet.row_values(i)
    variable = row[0] + row[1]
    print(" {0} {1}".format(row[0],format(row[1])))
    print(variable)

代码打印前两列。如何转换为字典类型?

首先,字典包含在 {} 而不是 [] 中,因此预期输出应该是 {'Sam' : 'Tester', 'John' : 'Developer', 'Fin' : 'Tester'}

此代码应该适合您:

my_dict = {}
for i in range(1, worksheet.nrows):
    row = worksheet.row_values(i)
    my_dict[row[0]] = row[1]

print(my_dict)