0

我正在尝试将 .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']}

我怎样才能重写代码,以使单个键(例如莎士比亚,威廉)具有他所写书籍的所有价值。为冗长的问题道歉。任何建议都将受到高度赞赏。

4

2 回答 2

1

只需更改 dict 以存储列表并继续附加特定作者姓名的值。

for line in _splitline:
    _line = line.split()
    Inventory.setdefault(_line[0]+","+_line[1], [])
    Inventory[_line[0]+","+_line[1]].append(_line[2:])
于 2013-11-08T06:16:25.613 回答
0

您应该添加一个 if 子句以查看该键是否已经存在,如果是这种情况,请增加字典中的值,而不是替换:

key = _line[0]+","+_line[1]
if key in Inventory:
    Inventory[key] = += _line[2:]
else:
    Inventory[key] = _line[2:]
于 2013-11-08T06:23:38.850 回答