python creating dictionary from excel

梦想的初衷 提交于 2020-01-23 07:48:32

问题


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} 

回答1:


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




回答2:


If your columns don't contain any data other than the names and ages and you're pretty confident about the data quality (no non-numeric data where ages should be, etc.) then you could go about it something like this:

names = (name.value for name in worksheet.col(0))
ages = (int(age.value) for age in worksheet.col(1))
data = dict(zip(names, ages))

If you want to guarantee order, you could use a collections.OrderedDict object for data instead of a vanilla dictionary.

If you need to handle bad data (i.e. someone entered a string instead of an integer age in the sheet), you may have to come up with custom implementations of the names and ages generator objects (the ones above assume smooth sailing).



来源:https://stackoverflow.com/questions/28414635/python-creating-dictionary-from-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!