Hi all

I'm needing help with a question in my tutorial due tomorrow...

I'm given this file which contains the following:

toy201, Racing Car, AB239:2,DC202:2,FR277:2,JK201:1,YU201:1,EE201:1,FW201:1
toy101, Barbie Doll, AB139:2,DC102:2,FR177:2,JK101:1,YU101:1,EE101:1,FW101:1
toy301, Flying Kite, AB339:2,DC302:2,FR377:2,JK301:1,YU301:1,EE301:1,FW301: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)........ }

Any help would be greatly appreciated...

i find (as far as i saw) u need a change after a comma(,).We will read the file character by character .When we encounter a comma we will go back and print the word..'word',n..something like this

A nice brain teaser to get to know Python, here are some hints:

"""wants dictionary object -->
{'toy301': ('Flying Kite', [('AB339',2),('DC302',2),('FR377',2),
('JK301),1),('YU301',1),('EE301',1),('FW301),1)])}
"""

# typical data line from a file
line = """\
toy301, Flying Kite, AB339:2,DC302:2,FR377:2,JK301:1,YU301:1,EE301:1,FW301:1
"""

# first split the line at the commas
list1 = line.split(",")
print(list1)

"""result -->
['toy301', ' Flying Kite', ' AB339:2', 'DC302:2', 'FR377:2',
'JK301:1', 'YU301:1', 'EE301:1', 'FW301:1\n']
"""

# next create a list of tuples from items that have ':'
tuple_list = []
for item in list1:
    # strip off trailing newline
    line = line.rstrip()
    if ':' in item:
        text, num = item.split(":")
        tuple_list.append((text, int(num)))

print(tuple_list)

"""result -->
[(' AB339', 2), ('DC302', 2), ('FR377', 2), ('JK301', 1),
('YU301', 1), ('EE301', 1), ('FW301', 1)]
"""

# now you are ready to piece together the dictionary object from
# parts in list1 and the tuple_list

Okay so 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_products('products.txt') it comes up with:

{'toy301': [(' AB339',2),('DC302',2),('FR377',2),('JK301),1),('YU301',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!

You are almost there, you need to indent properly to keep your statement blocks together ...

def load_products(filename):
    #filename = 'C:\Users\User\Desktop\cssetute\products.txt'
    f = open(filename, 'r')
    dictionary = {}
    for line in f.readlines():
        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)))
        # build the dictionary
        dictionary[list1[0]] = (list1[1], tuple_list)
    f.close()
    return dictionary

my_dict = load_products('products.txt')
print(my_dict)

"""my output (made somewhat pretty) -->
{'toy301': (' Flying Kite', 
[(' AB339', 2), ('DC302', 2), ('FR377', 2), ('JK301', 1), 
('YU301', 1), ('EE301', 1), ('FW301', 1)]),
'toy201': (' Racing Car', 
[(' AB239', 2), ('DC202', 2), ('FR277', 2), 
('JK201', 1), ('YU201', 1), ('EE201', 1), ('FW201', 1)]),
'toy101': (' Barbie Doll', 
[(' AB139', 2), ('DC102', 2), ('FR177', 2), 
('JK101', 1), ('YU101', 1), ('EE101', 1), ('FW101', 1)])}
"""

Make sure you don't use tabs for indents!

Add some print statements to see what is going on

def load_products(filename):
    filename = 'C:\Users\User\Desktop\cssetute\products.txt'
    f = open(filename, 'U')
    dictionary={}
    for line in f:
        line = line.rstrip()
        list1 = line.strip().split(',')
        print "list1 created =", list1

    tuple_list=[]

    print "searching list1", list1
    for item in list1:
 
       print "     item =", item
        if ':' in item:
            text, num = item.split(":")
            tuple_list.append((text, int(num)))
            print "     tuple_list =", tuple_list, "\n"

    dictionary[list1[0]] = tuple_list
    print "\ndictionary is now", dictionary, "\n"

    f.close()

    return dictionary

And if it easier to understand, use an additional function.

def add_to_dictionary(list_in, dictionary):
    tuple_list=[]

    for item in list_in:
        if ':' in item:
            text, num = item.split(":")
            tuple_list.append((text, int(num)))

    dictionary[list_in[0]] = tuple_list
    return dictionary

def load_products(filename):
    filename = 'C:\Users\User\Desktop\cssetute\products.txt'
    f = open(filename, 'U')
    dictionary={}
    for line in f:
        line = line.rstrip()
        list1 = line.strip().split(',')
     
        dictionary = add_to_dictionary(list1, dictionary)

    f.close()

Ahhhh I see, thanks so much everyone! Works perfect now.

This question has already been answered. Start a new discussion instead.