Reputation: 9
I am trying to import values from a .txt file into a dictionary and the code is shown below:
def displayInventory():
Inventory = {}
_openfile = open('database.txt','r+',)
_readfile = _openfile.read()
_readfile = _readfile.replace('$'," ")
print _readfile
_splitline = _readfile.split("\n")
for line in _splitline:
_line = line.split()
Inventory[_line[0]+","+_line[1]] = _line[2:]
print Inventory
It manages to import the different values into the dictionary but the problem that I am facing is this. There are certain values in the text file that end up having the same key. The values from the text file that are added to the dictionary overwrite the current values of the keys in the dictionary as shown below.
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
Dickens Charles David Copperfield 4 26.00
Austin Jane Emma 3 5.95
Hawthrone Nathaniel The Scarlet Letter 6 18.00
Shakespeare William Hamlet 10 6.99
Chaucer Geoffrey The Canterbury Tales 4 20.00
Dickens Charles Great Expectations 2 25.00
{'Hawthrone,Nathaniel': ['The', 'Scarlet', 'Letter', '6', '18.00'],
'Chaucer,Geoffrey': ['The', 'Canterbury', 'Tales', '4', '20.00'],
'Dickens,Charles': ['Great', 'Expectations', '2', '25.00'],
'Shakespeare,William': ['Hamlet', '10', '6.99'],
'Austin,Jane': ['Emma', '3', '5.95']}
How can I rewrite the code in a vay that a single key e.g. Shakespeare,William will have all the values of the books that he has written. Aplogies for the lengthy question. Any advice is highly appreciated.
Upvotes: 0
Views: 146
Reputation: 421
You should add an if clause to see if the key already exists, and if that is the case, increment the value in the dictionary, instead of replacing:
key = _line[0]+","+_line[1]
if key in Inventory:
Inventory[key] = += _line[2:]
else:
Inventory[key] = _line[2:]
Upvotes: 0
Reputation: 239653
Just change the dict to store a list and keep appending the values for the particular author name.
for line in _splitline:
_line = line.split()
Inventory.setdefault(_line[0]+","+_line[1], [])
Inventory[_line[0]+","+_line[1]].append(_line[2:])
Upvotes: 1