Reputation: 15
I'm trying to make a dictionary with actor names as keys, and the movies they're in as the value
The file looks like this:
Brad Pitt,Sleepers,Troy,Meet Joe Black,Oceans Eleven,Seven,Mr & Mrs Smith
Tom Hanks,You have got mail,Apollo 13,Sleepless in Seattle,Catch Me If You Can
And I want this to be the output:
{Brad Pitt : Sleepers,Troy,Meet Joe Black,Oceans Eleven,Seven,Mr & Mrs Smith
Tom Hanks : You have got mail,Apollo 13,Sleepless in Seattle,Catch Me If You Can}
I think my problem is that I can't access the file for some reason, although it's certainly possible there's some other problem with my code that I'm not seeing. Here's what I have:
from Myro import *
def makeDictionaryFromFile():
dictionary1={}
try:
infile = open("films.txt","r")
nextLineFromFile = infile.readline().rstrip('\r\n')
while (nextLineFromFile != ""):
line = nextLineFromFile.split(",")
first=line[0]
dictionary1[first]=line[1:]
nextLineFromFile = infile.readline().rstrip('\r\n')
except:
print ("File not found! (or other error!)")
return dictionary1
Upvotes: 1
Views: 98
Reputation: 19733
try this :
mydict = {}
f = open('file','r')
for x in f:
s = s.strip('\r\n').split(',')
mydict[s[0]] = ",".join(s[1:])
print mydict
s[0]
will have actor name, s[1:]
is all his films name
you using readline
readline only read a line.suppose below is a file called test.txt
Hello stackoverflow
hello Hackaholic
code:
f=open('test.txt')
print f.readline()
print f.readline()
output:
Hello stackoverflow
hello Hackaholic
you need to also put your readline
in side while loop, and you also need to do some other changes.
Upvotes: 0
Reputation: 12535
>>> dictionary1 = {}
>>> for curr_line in open("films.txt").xreadlines():
... split_line = curr_line.strip().split(",")
... dictionary1[split_line.pop(0)] = split_line
>>> dictionary1
{'Brad Pitt': ['Sleepers', 'Troy', 'Meet Joe Black', 'Oceans Eleven', 'Seven', 'Mr & Mrs Smith'], 'Tom Hanks': ['You have got mail', 'Apollo 13', 'Sleepless in Seattle', 'Catch Me If You Can']}
Upvotes: 0
Reputation: 3315
You need to start using the super helpful ipdb
module.
try:
# some error
except Exception as e:
print e
import ipdb
ipdb.set_trace()
If you get used to this process, it will help you a lot in this as well as future debugging.
Upvotes: 1