python - 尝试在 Python 中添加到字典时出现 ValueError

标签 python list file-io dictionary

所以我有一个这种格式的文件

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/

相关文章:

python - 如何进行编码(阿拉伯语 إعراب Parsing)Python?

python - 为什么在 cmd.Cmd 子类函数中退出 ipdb 会退出函数?

c# - 如果列表 A 中不存在该项目,则对列表 B 中的项目采取行动

java - 使用从命令行运行的命令在 Java 中使用 exec 进行编译和执行失败

python - 将缩略形式算作一个词

python - pandas 中的分组和转换

python - 以 "XX to XX"格式打印嵌套列表

r - 读取 json 文件时将嵌套列表转换为数据帧

Java .read() 函数返回什么?和Java IOException

java - 我应该在哪里放置 close() 方法?