countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]

countries_dict = {}
countries_new_list = []
for country_code, country in countries:
    print country_code
    countries_dict['country_code'] = country_code
    countries_new_list.append(countries_dict)

print countries_new_list


此代码将打印

AGO
PRT
[{'country_code': 'PRT'}, {'country_code': 'PRT'}]


我期望的是:

AGO
PRT
[{'country_code': 'AGO'}, {'country_code': 'PRT'}]


我在这里想念什么?

http://codepad.org/nZblGER7

最佳答案

我建议您在for循环中定义字典countries_dict

countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]
countries_new_list = []
for country_code, country in countries:
    print country_code
    countries_dict = {}
    countries_dict['country_code'] = country_code
    countries_new_list.append(countries_dict)

print countries_new_list

10-04 10:08