Jac*_*ahn 2 python dictionary file function
我有一个文本文件保存在记事本中,但移动到我的python文件夹,左边有一个国家的三个字母的缩写词,然后右边有四到五个空格,它有一个与之对应的国家:
AFG阿富汗
ARM亚美尼亚
等
我需要字典使用三个字母作为关键,而国家是价值.它有每个参加奥运会的国家.这是我的代码到目前为止的样子:
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')
Run Code Online (Sandbox Code Playgroud)
很可能一些国家(例如新西兰)在其名称中有多个单词,因此split()
返回的项目超过两个,但您试图将结果分配给两个变量,无论如何.限制split
为一:
key, value = line.split(None, 1)
Run Code Online (Sandbox Code Playgroud)
如果你发现你最后得到了多余的空白strip()
,那就扔一个:
key, value = line.strip().split(None, 1)
Run Code Online (Sandbox Code Playgroud)