首页 > 解决方案 > 将文件转换为字典?

问题描述

我有一个 txt 文件列出名称和年龄:

John,20
Mary,14
Kevin,60
Mary,15
John,40

并尝试编写以下函数来返回字典:

def read(filename):
    results = {}
    with open(os.path.join(os.path.dirname(__file__), 'data.txt')) as file:
        for line in file:
            location,value = line.split(',', 1)
            results[location] = value
        print(results)

我正在尝试格式化为:

{'John': [20, 40], 'Mary': [14, 15], 'Kevin': [60]}

但目前得到:

{'John': '20', 'Mary': '15\n', 'Kevin': '60\n'}

谁能帮我理解我做错了什么?

标签: pythondictionary

解决方案


您需要测试该键是否在字典中,如果没有则添加一个空列表。将当前值添加到键的列表中:

def read(filename):
    results = {}
    with open(os.path.join(os.path.dirname(__file__), 'data.txt')) as file:
        for line in file:
            if line.strip():     # guard against empty lines
                location,value = line.strip().split(',', 1)  # get rid of \n
                if location not in results:
                    results[location] = []
                results[location].append( int(value) )  # as number
        print(results)

如果需要,您可以查找dict.setdefault(key,defaultvalue)collections.defaultdict获得更多性能 - 在这里:collections.defaultdict 如何工作?


推荐阅读