Python 将单个列表添加到字典中,

Python 将单个列表添加到字典中,,python,list,dictionary,for-loop,Python,List,Dictionary,For Loop,我希望有人能在这里帮助我。我在将文本文件中的单个列表添加到字典中时遇到了一些严重的问题。文本文件中的列表显示为: 二十 硝烟 三十 辛普森一家 十, 威尔与格雷斯 十四, 达拉斯 二十 法律与秩序 十二, 谋杀,她写道 我需要的是每个条目,一次一行,成为键,然后是值。例如,它应该看起来像{20:硝烟,等等..} 根据我的指导老师,我必须使用file.readlines()方法。当前我的代码如下所示: # Get the user input inp = input() # creating f

我希望有人能在这里帮助我。我在将文本文件中的单个列表添加到字典中时遇到了一些严重的问题。文本文件中的列表显示为:

二十

硝烟

三十

辛普森一家

十,

威尔与格雷斯

十四,

达拉斯

二十

法律与秩序

十二,

谋杀,她写道

我需要的是每个条目,一次一行,成为键,然后是值。例如,它应该看起来像{20:硝烟,等等..}

根据我的指导老师,我必须使用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) 
输出如下所示:

# 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':无,'Gunsmome\n':无,'30\n':无,'Simpsons\n':无,'10\n':无,'Will&Grace\n':无,'14\n':无,'Dallas\n':无,'Law&Order\n':无,'12\n':无,'谋杀,她写道\n':无}

进程已完成,退出代码为0


这个问题还有很多,但我不是来找人帮我做作业的,我只是不知道如何正确地把这个加进去。我必须错过一些东西,我打赌这很简单。谢谢您的时间。

首先,您可以使用
read().splitlines()
读取文件而不使用换行符。然后将列表拆分为两个列表,每两个列表包含一个单词。然后将这两个列表压缩在一起,并从中创建字典:

# Get the user input
inp = input()

# creating file object.
f = open(inp)

# read the file into seperate lines.
mylist = f.readlines()

# determine the total number of key/value pairs
total_items = len(mylist)//2

# put the contents into a dictionary.
# note: strip() takes off the \n characters
mydict = {mylist[i*2].strip(): mylist[i*2+1].strip() for i in range(0,total_items)}

print(mydict) 
inp = input()
with open(inp, 'r') as f:
    mylist = f.read().splitlines()
    mydict = dict(zip(mylist[::2], mylist[1::2]))

另请注意:使用
with
可在完成后自动关闭文件。

这看起来确实可行,但我需要使用readlines()方法。是否可以从单个文本文件执行此操作?这似乎也简单得多。如果需要
readlines
,那么使用字典理解的另一个答案可能更合适。这太棒了,谢谢你的帮助!