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'}]
我在这里缺少什么?
答案 0 :(得分:4)
使用列表压缩的Pythonic方法: -
>>> countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]
>>> [{"country_code":i} for i ,j in countries]
[{'country_code': 'AGO'}, {'country_code': 'PRT'}]
>>>
答案 1 :(得分:3)
我建议你在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
答案 2 :(得分:1)
您的错误来自于您在countries_dict
中附加字典countries_new_list
而非副本。
您应该在for循环中执行countries_dict = {}
或使用副本:
from copy import copy
...
countries_new_list.append(copy(countries_dict))