python从excel创建字典 [英] python creating dictionary from excel

查看:53
本文介绍了python从excel创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 2 列的 Excel 表格.第 1 列是姓名,第 2 列是年龄.我想创建一个字典,其中名称是键,年龄是值.这是代码,但它错误地创建了字典.

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))

我想要一个来自 2 列 excel 表的字典.

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

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

推荐答案

pandas 很简单:

That's quite simple with pandas:

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

my_dic 现在是:

my_dic is now:

{'罗宾':4,'玛丽亚':3,'安':12}

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

index_col=0 如果 'name' 在您的 excel 文件的第一列中

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

这篇关于python从excel创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆