简体   繁体   中英

Convert columns of an Excel into dictionary in python

I have three columns in my excel file, i have to convert all the rows of the first two columns into a dictionary using xlrd.

Expected Output:

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

Excel文件的屏幕截图

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)

The code prints the first two columns. How to convert to dictionary type?

First thing, dictionary are enclosed in {} not [] so the expected output should be {'Sam' : 'Tester', 'John' : 'Developer', 'Fin' : 'Tester'}

This code should work for you:

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

print(my_dict)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM