简体   繁体   English

使用课程从.txt文件创建字典

[英]Creating a dictionary from a .txt file using courses

Write a program to create a dictionary that has the key-value pairs from the file "CourseInstructor.txt" I started to create a dictionary using the txt, file but receive the following error: 编写一个程序来创建一个字典,该字典具有来自文件“ CourseInstructor.txt”的键值对。我开始使用txt文件创建字典,但收到以下错误:

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

ValueError: not enough values to unpack (expected 2, got 1) ValueError:没有足够的值可解包(预期2,得到1)

You should do something like this: 您应该执行以下操作:

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

the best way to open files is with , it will close file after. 最好的打开文件方法是with ,它将在之后关闭文件。 the rstrip("\\n") will remove \\n from end of each line. rstrip("\\n")将从每行末尾删除\\n one more thing that you should know is your input file( CourseInstructor.txt ) should be like this: 您还应该知道的一件事是您的输入文件( CourseInstructor.txt )应该像这样:

key1 value1
key2 value2
key3 value3

If your file dose not contain new lines, use this: 如果您的文件不包含换行符,请使用以下命令:

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)) }

If your file looks like this: 如果您的文件如下所示:

key1 value1
key2 value2
key3 value3

you can try: 你可以试试:

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

Output: 输出:

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

File will eventually be closed when the file object is garbage collected. 当文件对象被垃圾回收时,文件最终将被关闭。 check this for more info. 检查此以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM