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

Python 从元组列表创建字典,输出错误,python,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(c

此代码将被打印

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'}]
我错过了什么


我建议您在for循环中定义字典
countries\u dict

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

我建议您在for循环中定义dictionary
countries\u dict

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

您的错误源于您在
countries\u new\u列表
中附加了单词序列
countries\u dict
,而不是副本

您应该在for循环中执行
countries\u 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

您的错误源于您在
countries\u new\u列表
中附加了单词序列
countries\u dict
,而不是副本

您应该在for循环中执行
countries\u 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

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

from copy import copy
...
countries_new_list.append(copy(countries_dict))

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

from copy import copy
...
countries_new_list.append(copy(countries_dict))

这是正确的答案。原始代码中发生的情况是,每次通过列表时,都会将对countries\u dict的引用附加到countries\u new\u列表中。当您打印列表时,无论您将其添加到列表中多少次,您都会得到countries_dict的当前状态。
countries_dict['country_code']=country_code
将country_code键的值更改为最后一项,因为dict是可变的。这是正确答案。原始代码中发生的情况是,每次通过列表时,都会将对countries\u dict的引用附加到countries\u new\u列表中。打印列表时,无论您将其添加到列表中多少次,都会得到countries\u dict的当前状态。
countries\u dict['country\u code']=country\u code
将country\u code键的值更改为最后一项,因为dict是可变的。