简体   繁体   English

将文件转换为字典?

[英]Converting file into dictionary?

I have an txt file listing name and age:我有一个 txt 文件列出名称和年龄:

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

And trying to write the below function to return a dictionary:并尝试编写以下 function 以返回字典:

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)

I'm trying to format as:我正在尝试格式化为:

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

But currently getting:但目前得到:

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

Can anyone help me understand what I'm doing wrong?谁能帮我理解我做错了什么?

You need to test if the key is in the dictionary, if not add an empty list.您需要测试该键是否在字典中,如果没有则添加一个空列表。 Add the current value to the list at the key:将当前值添加到键的列表中:

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)

You can lookup dict.setdefault(key,defaultvalue) and collections.defaultdict to get more performance if needed - fe here: How does collections.defaultdict work?如果需要,您可以查找dict.setdefault(key,defaultvalue)collections.defaultdict以获得更多性能 - 此处为: collections.defaultdict 如何工作?

You can try defaultdict:你可以试试defaultdict:

from collections import defaultdict

def read(filename):
results = deafultdict(list)
with open(os.path.join(os.path.dirname(__file__), 'data.txt')) as file:
    for line in file:
        location,value = line.split(',', 1)
        results[location].append(value.replace("\n", ""))

You will get:你会得到:

defaultdict(<class 'list'>, {'John': ['20', '40'], 'Mary': ['14', '15'], 'Kevin': ['60']})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM