尝试从文件制作python字典,但我不断收到类似'之类的错误,无法解包' [英] Trying to make a python dictionary from a file but I keep getting errors like 'too many values to unpack'

查看:31
本文介绍了尝试从文件制作python字典,但我不断收到类似'之类的错误,无法解包'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在记事本中保存了一个文本文件,但是将其移到我的python文件夹中,该文件夹的左边是一个国家的三个字母的首字母缩写,然后在右边约有四五个空格的位置具有与之对应的国家,如下所示:

I have a text file saved in notepad but moved into my python folder that has a three letter acronym for a country on the left and then about four or five spaces to the right it has the country that corresponds to it like so:

AFG阿富汗
ARM亚美尼亚

AFG Afghanistan
ARM Armenia
etc.

我需要字典使用三个字母作为键,而国家/地区是值.它有参加奥林匹克运动会的每个国家.到目前为止,这是我的代码:

I need the dictionary to use the three letters be the key and country be the value. It has every country that participates in the Olympics. Here's what my code looks like thus far:

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 限制为一个:

Most likely some of the countries (e.g. New Zealand) have more than one word in their names and so split() is returning more than two items, but you're trying to assign the results to two variables regardless. Limit the split to one:

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

如果发现最后得到多余的空格,请在其中扔 strip():

If you find you're getting excess whitespace at the end, throw a strip() in there:

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

这篇关于尝试从文件制作python字典,但我不断收到类似'之类的错误,无法解包'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆