尝试并解决实施问题

时间:2018-02-18 06:06:54

标签: python python-3.x python-2.7 python-requests try-catch

我收到了一份文件,其中包含国家列表及其所在的大陆。赋值的指令是使用try和except函数来生成带有各大洲键的字典,每个大陆的相应国家都是值。我设法使用for循环来解决这个问题,但我不知道如何使用try和except函数。我尝试过这样做,但是在测试程序时我收到了很多错误消息。我想知道如何实现try和except函数来解决赋值中的问题。

给我们的清单输出国家信息:

print(countries[0])

在这里,安道尔已经被选中,输出是:

{'timezones': ['Europe/Andorra'], 'code': 'AD', 'continent': 'Europe', 
'name': 'Andorra', 'capital': 'Andorra la Vella'}

我的代码:

from countries import countries
from pprint import pprint


continent_countries = {}
i=0

for country in countries:
#try:  
    continent_inputter = {country['continent']:[]}
    continent_countries.update(continent_inputter)
#except KeyError:
# print("TESTING. NONE. TRY AGAIN. ")

for country in countries:
    if 'Europe' == country['continent']:
        continent_countries['Europe'].append(country['name'])

    elif 'Oceania' == country['continent']:
        continent_countries['Oceania'].append(country['name'])

    elif 'Africa' == country['continent']:
        continent_countries['Africa'].append(country['name'])

    elif 'North America' == country['continent']:
        continent_countries['North America'].append(country['name'])

    elif 'South America' == country['continent']:
         continent_countries['South America'].append(country['name'])

    elif 'Asia' == country['continent']:
          continent_countries['Asia'].append(country['name'])
    i+=1

print(continent_countries)

1 个答案:

答案 0 :(得分:1)

for country in countries:
    continent = country['continent']
    if continent_countries.get(continent) is None:
        continent_countries[continent] = [country['name']]
    else:
        continent_countries[continent].append(country['name'])