从文本文件导入到字典

时间:2016-11-19 08:14:51

标签: python python-3.x dictionary

文件名:dictionary.txt

YAHOO:YHOO
GOOGLE INC:GOOG
Harley-Davidson:HOG
Yamana Gold:AUY
Sotheby’s:BID
inBev:BUD

代码:

infile = open('dictionary.txt', 'r')
content= infile.readlines()
infile.close()

counters ={}
for line in content:
        counters.append(content)
        print(counters)

我正在尝试将file.txt的内容导入到字典中。我已经搜索了堆栈溢出但请以简单的方式回答(不是打开...)

2 个答案:

答案 0 :(得分:0)

首先,不是明确打开和关闭文件,而是可以使用with语句打开文件,在块结束时自动关闭文件。

其次,由于文件对象是类似迭代器的对象(一次性可迭代),您可以循环遍历这些行并使用:字符拆分它们。您可以在dict函数中https://www.pubnub.com/blog/2015-07-22-getting-started-with-raspberry-pi-2-and-pubnub-in-python-programming-language/执行所有这些操作:

with open('dictionary.txt') as infile:
    my_dict = dict(line.strip().split(':') for line in infile)

答案 1 :(得分:0)

我认为你的钥匙上没有分号。 在这种情况下,你应该:

#read lines from your file
lines = open('dictionary.txt').read().split('\n')
#create an empty dictionary
dict = {}
#split every lines at ':' and use the left element as a key for the right value
for l in lines:
    content = l.split(':')
    dict[content[0]] = content[1]