我正在尝试将 .txt 文件中的值导入字典,代码如下所示:
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
它设法将不同的值导入字典,但我面临的问题是这个。文本文件中的某些值最终具有相同的键。添加到字典的文本文件中的值会覆盖字典中键的当前值,如下所示。
来自 database.txt 的值
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']}
我怎样才能重写代码,以使单个键(例如莎士比亚,威廉)具有他所写书籍的所有价值。为冗长的问题道歉。任何建议都将受到高度赞赏。