【问题标题】:Adding a single list into a dictionary,将单个列表添加到字典中,
【发布时间】: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


    【解决方案1】:
    # 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) 
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 这看起来确实可行,但需要使用 readlines() 方法。是否可以从单个文本文件中完成?这似乎也简单了很多。
      • 如果readlines 是一个要求,那么使用字典理解的其他答案可能更合适。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多