所以我有一个这种格式的文件
CountryCode CountryName
USA United States
我想做的是做一个字典,代码为键,国名为值。
我有一个函数,它有这样做的意图
def country(string):
'''reads the contents of a file into a string and closes it.'''
#open the file
countryDict = {}
fin = open(string, 'r')
for eachline in fin:
code, country = eachline.split()
countryDict[code] = country
print (countryDict)
return countryDict
但是,当我尝试运行它时,我得到了 ValueError:要解压的值太多(预期为 2)。
此代码不起作用的任何原因?我有一个类似的程序可以使用这样的代码创建用户名。
供引用的用户名程序代码,这个可以用,上面为什么不行:
def main():
print ("This program creates a file of usernames from a")
print ("file of names.")
# get the file names
infileName = input("What file are the names in? ")
outfileName = input("What file should the usernames go in? ")
# open the files
infile = open(infileName, 'r')
outfile = open(outfileName, 'w')
# process each line of the input file
for line in infile:
# get the first and last names from line
first, last = line.split()
# create a username
uname = (first[0]+last[:7]).lower()
# write it to the output file
print(uname, file=outfile)
# close both files
infile.close()
outfile.close()
print("Usernames have been written to", outfileName)
if __name__ == '__main__':
main()
最佳答案
想想什么时候 line
是:
USA United States
当你拆分它时,它会创建:
['USA', 'United', 'States']
当您执行 first, last = line.split()
时,它会尝试将三个值放入两个变量中(因此出现错误)。
为防止这种情况,您可以拆分一次:
>>> first, last = 'USA United States'.split(None, 1)
>>> first
'USA'
>>> last
'United States'
关于python - 尝试在 Python 中添加到字典时出现 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17692700/