gpt4 book ai didi

python - 尝试从文件制作 python 字典,但我不断收到类似 'too many values to unpack' 的错误

转载 作者:行者123 更新时间:2023-11-28 19:39:52 27 4
gpt4 key购买 nike

我在记事本中保存了一个文本文件,但移到了我的 python 文件夹中,该文件夹的左侧是一个国家/地区的三个字母首字母缩写词,然后在右侧大约有四个或五个空格,它具有与之对应的国家/地区,如下所示:

AFG Afghanistan
ARM Armenia
etc.

我需要字典使用三个字母作为键,国家/地区作为值。它拥有参加奥运会的每个国家。到目前为止,这是我的代码的样子:

def country(fileName):
infile = open(fileName,'r')
countryDict = {}
for line in infile:
key,value = line.split()
countryDict[key] = value
print(countryDict)
return countryDict
country('CountryCodes.txt')

最佳答案

很可能某些国家(例如新西兰)的名称中有多个单词,因此 split() 返回了两个以上的项目,但您正在尝试分配结果两个变量不管。将 split 限制为一个:

key, value = line.split(None, 1)

如果你发现最后有多余的空格,请在其中添加一个 strip():

key, value = line.strip().split(None, 1)

关于python - 尝试从文件制作 python 字典,但我不断收到类似 'too many values to unpack' 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17653954/

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