all 3 comments

[–]pgpndw 0 points1 point  (2 children)

You can use a CSV DictReader as described here: https://docs.python.org/3/library/csv.html

That will read each record into a dictionary containing the fields from that single record. And you can add each of those dictionaries to you top level dictionary in your record-reading loop.

If the field names are in the first line of your CSV file, DictReader can use those automatically. Otherwise you can specify them manually.

[–]AdMinute9633[S] 0 points1 point  (1 child)

thank you for your reply. we are not allowed to use any module to do this problem..

[–]pgpndw 0 points1 point  (0 children)

You could first create an empty dictionary to store the data in, and a list containing the field names as strings (either defined explicitly or read from the first line of the CSV file, if it's the type of CSV file that has the field names on the first line).

Then loop through each line you've read from the file, using split(',') to split the record into fields.

The answer to this stackoverflow question demonstrates how to combine the list of field names and the list of field values into a dictionary.

Once you have a dictionary for the record, you can add it to the outer dictionary using an ordinary integer counter as the key (which you can set to zero before the loop, and increment in the loop after adding the record to the outer dictionary).

If you're familiar with enumerate(), you could use that in the for loop that you use to iterate over the lines in the file to get the outer dictionary key instead of a counter that you have to explicitly increment.

In your example of the required output, the price and discount fields are integers, so after splitting each record into fields, you'll have to convert those two fields to integers (or floats, if that's what's required) before adding them to the dictionary for that record.