【发布时间】:2021-05-22 21:44:31
【问题描述】:
我希望有人可以在这里帮助我。我在将单个列表从文本文件添加到字典时遇到了一些严重的问题。文本文件中的列表显示为:
20
枪烟
30
辛普森一家
10
威尔和格蕾丝
14
达拉斯
20
法律与秩序
12
谋杀,她写道
我需要的是让每个条目,一次一行,成为键,然后是值。例如,它应该看起来像 {20:Gunsmoke, etc...}
根据我的导师,我必须使用 file.readlines() 方法。目前我的代码如下所示:
# Get the user input
inp = input()
# creating file object.
open = open(inp)
# read the file into seperate lines.
mylist = open.readlines()
# put the contents into a dictionary.
mydict = dict.fromkeys(mylist)
print(mydict)
输出如下:
file1.txt {'20\n':无,'Gunsmoke\n':无,'30\n':无,'辛普森一家\n':无,'10\n':无,'Will & Grace\n':无,'14\n':无,'达拉斯\n':无,'法律与秩序\n':无,'12\n':无,'谋杀,她写\n':无}
进程以退出代码 0 结束
这个问题还有很多,但我不是来找人做作业的,我只是不知道如何正确添加。我必须错过一些东西,我打赌它很简单。感谢您的宝贵时间。
【问题讨论】:
标签: python list dictionary for-loop