【问题标题】:Creating a dictionary from a .txt file using courses使用课程从 .txt 文件创建字典
【发布时间】:2018-04-09 03:34:21
【问题描述】:

编写一个程序来创建一个字典,其中包含文件中的键值对 “课程讲师.txt” 我开始使用 txt, 文件创建字典,但收到以下错误:

Course=("CourseInstructor.txt",'r')
for line in Course:
    key,val = line.split(" ")
    Inst[key] = val
Course.close()

ValueError: 没有足够的值来解包(预期 2,得到 1)

【问题讨论】:

  • 你也可以发布你的文件吗?
  • 您从未打开过该文件。你在("CourseInstructor.txt",'r')前面错过了open
  • 我猜你的文件CourseInstructor.txt 没有包含足够的数据。

标签: python


【解决方案1】:

你应该这样做:

Inst = dict()
with open("CourseInstructor.txt",'r') as Course:
    for line in Course:
        key,val = line.rstrip("\n").split(" ")
        Inst[key] = val

打开文件的最佳方式是with,之后它会关闭文件。 rstrip("\n") 将从每行的末尾删除 \n。 你应该知道的另一件事是你的输入文件(CourseInstructor.txt)应该是这样的:

key1 value1
key2 value2
key3 value3

如果您的文件不包含新行,请使用:

your_string = your_string.split(" ")
keys = [i for i in your_string[::2]]
values = [i for i in your_string[1::2]]
final_dict = {keys[i]:values[i] for i in range(len(values)) }

【讨论】:

  • 我试过了,它仍然给我同样的错误:ValueError: not enough values to unpack (expected 2, got 1)
  • 对于这行代码:key,val = line.rstrip("\n").split(" ")
  • 请发布您的文件内容。 @Nat
  • CIS2200 Izen CIS3100 Ennoure CIS3120库马尔CIS3400蕨类CIS3750 Gubernat CIS3920柴CIS4100弗里德曼CIS4110芬尼根CIS4160克雷格CIS4400 Holowczak CIS4800芬尼根CIS5800布朗CIS9340克莱恩CIS9440 Holowczak CIS9480 Bianco的CIS9490 Kiris CIS9557库马尔CIS9660高跨度>
  • 但并非全部在一行
【解决方案2】:

如果您的文件如下所示:

key1 value1
key2 value2
key3 value3

你可以试试:

print({line.split()[0]:line.split()[1] for line in open('file','r')})

输出:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

当文件对象被垃圾回收时,文件最终将被关闭。 check this 了解更多信息。

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多