Skip to main content
 首页 » 编程设计

python之从元组列表创建字典,输出错误

2025年05月04日11mate10pro

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

请您参考如下方法:

使用列表压缩的Pythonic方式:-

>>> countries = [('AGO', 'ANGOLA'), ('PRT', 'PORTUGAL')] 
>>> [{"country_code":i} for i ,j in countries] 
[{'country_code': 'AGO'}, {'country_code': 'PRT'}] 
>>>