我正在尝试编写一个从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
答案 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