0

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:

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)

Jess12
  • 25
  • 5

2 Answers2

3

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. the rstrip("\n") will remove \n from end of each line. one more thing that you should know is your input file(CourseInstructor.txt) should be like this:

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)) }
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

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.

Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88