0

I'm trying to let the dictionary called

theInventory = {}

to sort the following items, so i can add price or view the books by authors and etc.

It's my homework problem. so i need to use dictionary and multi-value using 2D list

Let the some text file called database.txt contains

last name/first name/quantity/price

Shakespeare,William,Romeo And Juliet,5,5.99

Shakespeare,William,Macbeth,3,7.99

Dickens,Charles,Hard Times,7,27.00

Austin,Jane,Sense And Sensibility,2,4.95

Is it possible to do the following?

inFile = (database.txt, "r")
For line in inFile:
    aLine = []
    aLine = line.split(",") # dont know how to split by ,
    theInventory[aLine[0] + ", " + aLine[1]] = list[list[aLine[3], int(aLine[4]), float(aLine[5])]]

inFile.close()

the result will be like

>print (theInventory)
>> {"Shakespeare, William": [["Romeo And Juliet", 5, 5.99], ["Macbeth", 3, 7.99]], "Dickens, Charles": [["Hard Times", 7, 27.00]], "Austin, Jane": [["Sense And Sensibility", 2, 4.95]]}

so that you can modify quantity and price of the certain book.

or even add books to dictionary.

tshepang
  • 10,772
  • 21
  • 84
  • 127
Bryan B
  • 3
  • 3

1 Answers1

0

the file looks like a CSV file. Python has a module named as csv which enables the user to read/write rcsv files. Below is the example code as given in the python document.

import csv
with open('database.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
    for row in reader:
        print row

output:

['Shakespeare', 'William', 'Romeo And Juliet', '5', '5.99']
['Shakespeare', 'William', 'Macbeth', '3', '7.99']
['Dickens', 'Charles', 'Hard Times', '7', '27.00']
['Austin', 'Jane', 'Sense And Sensibility', '2', '4.95']
>>> 

more information about the csv module can be found here:https://docs.python.org/2/library/csv.html

edit: this is something very basic, but might given you an idea

import csv

dicto = {}
name = ''
#dicto[name] = []
with open('database.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
    for row in reader:
        name = row[0] + ',' + row[1] # frames the name
        if name in dicto.keys(): # checks if the name exists in the dictionary , if yes just append the book 
            books = dicto.get(name)
            books.append(row[2:])
        else: # if no entry of author is made, create new book list
            books = []
            books.append(row[2:])
        dicto[name] =books # update the list of books

    print dicto

output:

{'Dickens,Charles': [['Hard Times', '7', '27.00']], 'Shakespeare,William': [['Romeo And Juliet', '5', '5.99'], ['Macbeth', '3', '7.99']], 'Austin,Jane': [['Sense And Sensibility', '2', '4.95']]}
durga
  • 384
  • 4
  • 11
  • Thank you for he information but I need to use dictionary so in the later programming, when i call the author Shakespeare, it both display Romeo And Juliet, and Macbeth information. like a Key: Value – Bryan B May 06 '14 at 06:12