I am working on a small exercise.
There is a text file which has 3 columns: EmployeeID, First Name and Last Name. Write a program to create dictionary whose
keys()
are the EmployeeIDs in the text file and thevalues()
are the first and last names combined.
I tried first without loop.
f = open('empID.txt','r')
line1 = f.readline().split()
line2 = f.readline().split()
line3 = f.readline().split()
print line1
print line2
print line3
empdict={}
empdict[line1[0]] = line1[1]+" "+line1[2]
empdict[line2[0]] = line2[1]+" "+line2[2]
empdict[line3[0]] = line3[1]+" "+line3[2]
print "The resulting dictionary is \n",empdict
f.close()
This worked fine. Then I tried loop.
f = open('empID.txt','r')
empdict = {}
for line in f:
line = f.readline().split()
print line
empdict[line[0]] = line[1]+" "+line[2]
print "The resulting dictionary is \n",empdict
f.close()
This threw an error:
Traceback (most recent call last):
File "empID3.py", line 4, in <module>
line = f.readline().split()
ValueError: Mixing iteration and read methods would lose data
Somebody advised on a similar situation to use while
loop instead, so I tried:
In place of for line in f:
, I added while True:
and this time it printed all line
outputs and then threw another error instead of outputting the dictionary
.
Traceback (most recent call last):
File "empID3.py", line 6, in <module>
empdict[line[0]]=line[1]+" "+line[2]
IndexError: list index out of range
Can somebody help me get this right? Where am I wrong?