Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文件转换为字典?_Python_Dictionary - Fatal编程技术网

Python 将文件转换为字典?

Python 将文件转换为字典?,python,dictionary,Python,Dictionary,我有一个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

我有一个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'}


有人能帮我理解我做错了什么吗?

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

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
,以获得更高的性能,如果需要的话-f.e.这里:

您可以尝试使用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", ""))
您将获得:

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

而不是此行
results[location]=value
您需要输入if station,并检查location键是否已经存在。如果是,则附加新值。如果不是
结果[位置]=[值]