Chr*_*ael 7 python dictionary python-2.7
所以我有一个文本文件,如下所示:
apples,green
tomatos,red
bananas,yellow
Run Code Online (Sandbox Code Playgroud)
我用它作为字典的代码是
def load_list(filename):
with open(filename, "rU") as my_file:
my_list = {}
for line in my_file:
x = line.split(",")
key = x[0]
value = x[1]
my_list[key] = value
print my_list
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,但由于换行符,每个值都添加到它的末尾.我尝试添加
.strip()
Run Code Online (Sandbox Code Playgroud)
到x属性,但它在属性错误中被重新出现(AttributeError:'dict'对象没有属性'strip').
那么如何删除\n?
the*_*eye 11
你应该strip
在分裂之前,像这样
x = line.rstrip("\n").split(",")
Run Code Online (Sandbox Code Playgroud)
我们str.rstrip
在这里使用,因为我们只需要在行尾消除换行符.
此外,您可以立即解开密钥和值,就像这样
key, value = line.rstrip("\n").split(",")
Run Code Online (Sandbox Code Playgroud)