无法从pygal.maps.world.COUNTRIES中提取国家/地区代码

时间:2018-12-27 16:09:08

标签: python

我正在尝试编写一个从pygal.maps.world.COUNTRIES提取两位数字的国家/地区代码的函数,但是该函数不能始终如一地工作。我的代码:

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
"""Return the Pygal 2-digit country code for the given country"""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        # If the country wasn't found, return None.
        return None

在进行以下测试时:

print(get_country_code('Andorra'))
print(get_country_code('Afghanistan'))
print(get_country_code('United Arab Emirates'))

我得到结果:

ad
None
None

2 个答案:

答案 0 :(得分:3)

您的for循环总是在第一次迭代后返回,因为您错误地缩进了return None,因此它是for循环的一部分。

这应该有效:

def get_country_code(country_name):
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    # If the country wasn't found, return None.
    return None

答案 1 :(得分:2)

这不能直接回答您的问题,但是您可以使用pycountry轻松地做到这一点:

rowFromGrid.Cells