Python Dictionary文件没有翻译成数组

时间:2017-09-01 11:53:29

标签: python

我正在加载一个文件,其中的文字和定义各自以冒号分隔。这是一个样本。

Dissaray:A state of confusion and disorderliness
Staid:Steady and serious
Contemptible:Unworthy, wretched, mean
Intertwine:To connect or associate two things
Unwarranted:Not based on truth or valid circumstances
Punctuate:To specifically point out
Validate:To state the soundness or truth of something
Conducive:To contribute in a useful way

我正在尝试使用以下代码读取文件:

print("Currently loading file for your level")
dictionary = {}
with open("level"+str(level)+".txt","r+") as f:
    for line in f:
        print line
        line.split(":")
        dictionary[line[0]] = line[1]
print("Dictionary file has been loaded")
print(dictionary)

线条打印正确,但是当我打印dictionary数组时,我得到了这个。 {'A': 'p', 'C': 'o', 'B': 'e', 'E': 'm', 'D': 'e', 'G': 'r', 'F': 'i', 'I': 'r', 'H': 'i', 'J': 'o', 'M': 'i', 'L': 'u', 'O': 'p', 'N': 'o', 'P': 'a', 'S': 'u', 'R': 'e', 'U': 'n', 'T': 'r', 'W': 'a', 'V': 'e', 'Z': 'e'}

我不确定这里发生了什么,有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

str.split无法正常工作。您需要将其分配给line,否则,您将索引原始行:

for line in f:
   line = line.split(":")
   dictionary[line[0]] = line[1]

更多的是,您也可以这样做:

dictionary = dict(line.split(':') for line in f)

从生成器表达式构建字典。

答案 1 :(得分:2)

问题是.split()返回其值而不是修改其参数。实际上它必须这样做,因为字符串在Python中是不可变的。所以你只需要改变:

line.split(":")
dictionary[line[0]] = line[1]

line_parts = line.split(":")
dictionary[line_parts[0]] = line_parts[1]