我正在尝试通过从看起来像这样的文本文件中提取来创建字典,
Fred beats Amy
Fred beats Tom
Tom beats Amy
Amy beats Jordan
我现在正在用
f = open("RockPaperScissors.txt", 'r')
fwDict = {}
for line in f:
k, v = line.strip().split('beats')
fwDict[k.strip()] = v.strip()
f.close()
我遇到的问题是,当“Fred”多次出现时,它只是覆盖以前的值 (Amy) 并用最新的值 (Tom) 替换它,有什么办法可以添加一个新值如果 key 已经存在,即使从 txt 文件中提取?
谢谢!
请您参考如下方法:
您可以用列表替换字典的值:
f = open("RockPaperScissors.txt", 'r')
fwDict = {}
for line in f:
k, v = line.strip().split('beats')
# If we already have the key in the dictionary, just append to the list
if k.strip() in fwDict:
fwDict[k.strip()].append(v.strip())
# If we don't have the key in the dict, create the new key-value pair as a list
else:
fwDict[k.strip()] = [v.strip()]
f.close()
