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'}]
我在这里错过了什么?
请您参考如下方法:
使用列表压缩的Pythonic方式:-
>>> countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')]
>>> [{"country_code":i} for i ,j in countries]
[{'country_code': 'AGO'}, {'country_code': 'PRT'}]
>>>
