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

时间:2015-03-02 11:08:18

标签: python

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

3 个答案:

答案 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))