我正在尝试将数据从 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/