Python:使用相同的键将不同的值导入字典
我正在尝试将.txt文件中的值导入字典,代码如下所示:Python:使用相同的键将不同的值导入字典,python,dictionary,Python,Dictionary,我正在尝试将.txt文件中的值导入字典,代码如下所示: def displayInventory(): Inventory = {} _openfile = open('database.txt','r+',) _readfile = _openfile.read() _readfile = _readfile.replace('$'," ") print _readfile _splitline = _readfile.split(
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中的值
库存字典键和值
我怎样才能在一个关键时刻重写代码,例如莎士比亚,威廉将拥有他所写书籍的全部价值。
对这个冗长问题的回答。
非常感谢您的建议。只需更改dict以存储列表,并继续为特定作者姓名添加值即可
for line in _splitline:
_line = line.split()
Inventory.setdefault(_line[0]+","+_line[1], [])
Inventory[_line[0]+","+_line[1]].append(_line[2:])
您应该添加一个if子句来查看键是否已经存在,如果已经存在,则增加字典中的值,而不是替换:
key = _line[0]+","+_line[1]
if key in Inventory:
Inventory[key] = += _line[2:]
else:
Inventory[key] = _line[2:]
for line in _splitline:
_line = line.split()
Inventory.setdefault(_line[0]+","+_line[1], [])
Inventory[_line[0]+","+_line[1]].append(_line[2:])
key = _line[0]+","+_line[1]
if key in Inventory:
Inventory[key] = += _line[2:]
else:
Inventory[key] = _line[2:]