PDA

View Full Version : What's wrong with my dictionary code? Help please!



Ally89
September 4th, 2009, 01:51 AM
Okay so I'm just beginning!

I'm given this file which contains the following:

toy201, Racing Car, AB239:2,DC202:2,FR277:2,JK201:1,YU201:1,EE201:1,FW 201:1
toy101, Barbie Doll, AB139:2,DC102:2,FR177:2,JK101:1,YU101:1,EE101:1,FW 101:1
toy301, Flying Kite, AB339:2,DC302:2,FR377:2,JK301:1,YU301:1,EE301:1,FW 301:1

I am now to define a function that gives the following from the above file:

>>>load_prods(filename)
{'toy301': ('Flying Kite', [('AB339',2),('DC302',2),('FR377',2),('JK301),1),(' YU301',1),('EE301',1),('FW301),1)])

.......(and the same for barbie doll and flying kite)........ }


So far I have:

def load_products(filename):
filename = 'C:\Users\User\Desktop\cssetute\products.txt'
f= open(filename, 'U')
dictionary={}
for line in f:
list1 = line.strip().split(',')
tuple_list=[]
for item in list1:
line = line.rstrip()
if ':' in item:
text, num = item.split(":")
tuple_list.append((text, int(num)))
dictionary[list1[0]] = tuple_list
f.close()
return dictionary


But when i load_prods('products.txt') it comes up with:

{'toy301': [(' AB339',2),('DC302',2),('FR377',2),('JK301),1),('YU 301',1),('EE301',1),('FW301),1)]}

The name of the toy is missing and only one line comes up when I need the whole three toy lines to come up.
Help thanks!

smartbei
September 4th, 2009, 10:15 AM
Firstly, please post code in [code ] [/code ] tags (without the spaces). This makes it look nice and keeps indentation.

Secondly, This question is eerily similar to a similar question posted by stackee a day or two ago. That thread is still active, so you might want to take a look at it. LINK (http://ubuntuforums.org/showthread.php?t=1256718)