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)

3
  • Can u post your file as well.? Commented Apr 9, 2018 at 3:35
  • 4
    You never opened the file. You missed open in front of ("CourseInstructor.txt",'r'). Commented Apr 9, 2018 at 3:36
  • I guess your file CourseInstructor.txt don't contain enough data. Commented Apr 9, 2018 at 3:36

2 Answers 2

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)) } 
Sign up to request clarification or add additional context in comments.

7 Comments

I tried that and it is still giving me the same error :ValueError: not enough values to unpack (expected 2, got 1)
For this line of code: key,val = line.rstrip("\n").split(" ")
please post you file content. @Nat
CIS2200 Izen CIS3100 Ennoure CIS3120 Kumar CIS3400 Ferns CIS3750 Gubernat CIS3920 Cai CIS4100 Friedman CIS4110 Finnegan CIS4160 Craig CIS4400 Holowczak CIS4800 Finnegan CIS5800 Brown CIS9340 Kline CIS9440 Holowczak CIS9480 Bianco CIS9490 Kiris CIS9557 Kumar CIS9660 Gao
but it isn't all in one line
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.