python - 将 Excel 文件中的数据转换为 Python 字典

标签 python excel dictionary

我正在尝试将数据从 Excel 文件转换为 Python 字典。我的 Excel 文件有两列和许多行。

Name    Age
Steve   11
Mike    10
John    11

如何将其添加到以 Age 为键、以 name 为值的字典中?另外,如果许多名字具有相同的年龄,那么它们都应该在一个数组中。例如:

{'11':['Steve','John'],'10':['Mike']}

到目前为止我所写的内容:

import xlsxwriter
import openpyxl

wb = openpyxl.load_workbook('demo.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

#print sheet.cell(row=2, column=2).value


age_and_names = {}

for i in range(1,11):

    age = sheet.cell(row=i, column=2).value
    name = sheet.cell(row=i, column=1).value  

#Problem seems to be in this general area
    if not age in age_and_names:
        age_and_names[age]=[]

        age_and_names[age].append(name)    

print age_and_names

为了获得所需的输出,我应该做什么?我对 python 很陌生。所有帮助将不胜感激。谢谢。

最佳答案

只是一个简单的缩进错误,您的代码不正确

#Problem seems to be in this general area
    if not age in age_and_names:
        age_and_names[age]=[]
        age_and_names[age].append(name)    

应该是

#Problem seems to be in this general area
    if not age in age_and_names:
        age_and_names[age]=[]

    age_and_names[age].append(name)    

否则,您将销毁 age_and_names[age] 中以前的数据。

您应该考虑使用collections.defaultdict来避免测试 key 是否存在:

这样声明

from collections import defaultdict

age_and_names = defaultdict(list)

像这样使用:

age_and_names[12].append("Mike")

如果字典没有键12,它将调用list方法并为您创建一个空列表。无需首先测试 key 是否存在。

关于python - 将 Excel 文件中的数据转换为 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39027559/

相关文章:

python - 在ming中创建连接之前声明模型

python - 南方(对于Django)可以将数据行插入数据库吗?

asp.net-mvc - EPPlus 失去行高

vba - isEmpty() 总是返回 false

python - 三层嵌套字典的存在性检验

python - 如何从列表中删除最后一次出现的项目?

Python在每个元音前添加字符串

html - vba 中的 Web Scraping - 构造工作数据并从左到右单元格写入

c++ - map 的内积

algorithm - 基于字典的压缩算法的最佳子串选择