【问题标题】:Creating a dictionary from CSV data从 CSV 数据创建字典
【发布时间】:2013-05-16 08:49:35
【问题描述】:

我有一个函数,它接受一个 CSV 文件并将其拆分为 3 个值;然后isbnauthortitle 创建一个字典,将isbn 值映射到包含authortitle 的元组。这是我当前的代码:

def isbn_dictionary(filename):
    file = open(filename, 'r')
    for line in file:
        data = line.strip('\n')
        author, title, isbn = data.split(',') 
        isbn_dict = {isbn:(author, title)}
        print(isbn_dict)

问题是目前我可以让它为每个isbn 创建一个字典,但不能为所有这些创建一个字典。我目前的输出是:

{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions')}
{'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip')}
{'1-877270-02-4': ('Joe Bennett', 'So Help me Dog')}
{'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}

我的输出应该是什么:

{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions'),
'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip'),
'1-877270-02-4': ('Joe Bennett', 'So Help me Dog'),
'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}

这可能是一个非常简单的问题,但我无法理解它。

【问题讨论】:

    标签: python dictionary python-3.x


    【解决方案1】:

    使用csv module 进行更轻松、更高效的处理以及字典理解:

    import csv
    
    def isbn_dictionary(filename):
        with open(filename, newline='') as infile:
            reader = csv.reader(infile)
            return {isbn: (author, title) for isbn, author, title in reader}
    

    您的代码每行只创建了一个字典,并且只打印了字典。您可能想返回字典。

    使用字典推导不仅使函数更紧凑,而且效率更高。字典是在 C 代码中一次性创建的,而不是在 Python 循环中一一添加键和值。

    【讨论】:

    • 感谢您的回答。我应该注意到在我的代码中,我实际上应该返回而不是打印。
    • 虽然@AlcariTheMad 修复了 OP 代码中的错误,但这是最 Pythonic 的答案
    【解决方案2】:

    你需要在循环之前声明isbn_dict,像这样:

    def isbn_dictionary(filename):
        file = open(filename, 'r')
        isbn_dict = {}
        for line in file:
            data = line.strip('\n')
            author, title, isbn = data.split(',') 
            isbn_dict[isbn] = (author, title)
        print(isbn_dict)
    

    这样,每个项目都会添加到现有字典中。

    【讨论】:

    • 与 OP 一样,您实际上并不 return 生成的字典。打印是一个不错的调试工具,但并没有使该功能非常有用。
    • @AlcariTheMad 你也应该close文件
    • @AlcariTheMad 感谢您的回答,我知道这会相对简单。
    • 最好使用with open(...) as localname:,这样with块结束时文件会自动关闭。
    • @MartijnPieters 谢谢,我没想到,我会记住的
    猜你喜欢
    • 1970-01-01
    • 2016-11-20
    • 2018-12-05
    • 2016-09-03
    • 2011-10-08
    • 2012-12-15
    • 2021-02-20
    • 2012-01-02
    相关资源
    最近更新 更多