Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python creating dictionary from excel

I have an excel sheet with 2 columns. Column 1 is name, and Column 2 is age. I want to create a dictionary where name is key and age is value. Here is the code, but it is creating a dictionary incorrectly.

keyValues = [x.value for x in worksheet.col(0)]
data = dict((x, []) for x in keyValues)
while curr_row < num_rows:
        curr_row += 1
        for row_index in range(1, worksheet.nrows):  data[keyValues[row_index]].append(worksheet.cell_value(curr_row, 1))

I want to have a dictionary like below coming from 2 columns of excel sheet.

{'Ann': 12, 'Maria': 3, 'Robin': 4, 'NameN':N} 
like image 277
user1651888 Avatar asked Mar 18 '23 02:03

user1651888


1 Answers

That's quite simple with pandas:

import pandas as pd
my_dic = pd.read_excel('names.xlsx', index_col=0).to_dict()

my_dic is now:

{'Robin': 4, 'Maria': 3, 'Ann': 12}

index_col=0 if 'name' is in the first column of your excel file

like image 200
Marek Avatar answered Mar 23 '23 09:03

Marek