我试图将文件的内容存储到字典中,并且我想在调用其键时返回一个值。文件的每一行都有两个用逗号分隔的项目(首字母缩略词和相应的短语),并且有585行。我想将逗号左侧的缩略词存储到键中,并将逗号右侧的短语存储为值。下面是我有:读取文件并将内容存储到字典中 - Python
def read_file(filename):
infile = open(filename, 'r')
for line in infile:
line = line.strip() #remove newline character at end of each line
phrase = line.split(',')
newDict = {'phrase[0]':'phrase[1]'}
infile.close()
这里就是我得到的,当我尝试查找值:
>>> read_file('acronyms.csv')
>>> acronyms=read_file('acronyms.csv')
>>> acronyms['ABT']
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
acronyms['ABT']
TypeError: 'NoneType' object is not subscriptable
>>>
如果我添加return newDict
到函数体的最后,它显然只是当我拨打read_file('acronyms.csv')
时,返回{'phrase[0]':'phrase[1]'}
。我也试过{phrase[0]:phrase[1]}
(没有单引号),但是返回相同的错误。谢谢你的帮助。
我加入了蟒蛇标记你的问题,使得Python程序员就可以找到它。 – timgeb