【问题标题】:Convert data from an excel file into a python dictionary将excel文件中的数据转换成python字典
【发布时间】:2016-08-19 05:14:39
【问题描述】:

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

Name    Age
Steve   11
Mike    10
John    11

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

{'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很陌生。所有帮助将不胜感激。谢谢你。

【问题讨论】:

    标签: python excel dictionary


    【解决方案1】:

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

    #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 来避免测试密钥是否存在:

    这样声明

    from collections import defaultdict
    
    age_and_names = defaultdict(list)
    

    这样使用:

    age_and_names[12].append("Mike")
    

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

    【讨论】:

    • 此代码有效,但键和值周围都有奇怪的字符:{1L: [u'dmvyc'], 4L: [u'aorbe', u'ebphb', u'nprrj'], 5L: [u'fgyfg'], 6L: [u'ralno'], 7L: [u'zaysd', u'wmklg', u'gsdhy', u'cqiki']}
    • 这是字典的表示,不用担心,如果你打印每个元素,你不会得到它。 (u 代表 unicode,L 代表长整数)
    • 没有,即使我打印print age_and_names[6] 它也会打印[u'ralno']
    • @Di437 那是因为您正在打印列表。如果您只想要列表中的一个元素,则必须在列表中建立索引:print age_and_names[6][0] 此外,您可能应该使用 Python 3。
    【解决方案2】:

    对于这种情况,使用collections.defaultdict 而不是普通字典{}); collections.defaultdict 采用工厂函数,用于构造新键的值。使用list为每个键构造一个空列表:

    import collections
    age_and_names = collections.defaultdict(list)
    
    ...
         age_and_names[age].append(name)
    

    不需要ifs。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-28
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多