gpt4 book ai didi

python - 从文本文件导入数据时向预先存在的字典键添加值 (Python 3)

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:34 24 4
gpt4 key购买 nike

我正在尝试通过从看起来像这样的文本文件中提取来创建字典,

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()

关于python - 从文本文件导入数据时向预先存在的字典键添加值 (Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43396175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com