繁体   English   中英

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

[英]Create dictionary from list of tuples, wrong output

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

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

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

我建议你定义词典countries_dict里面的for循环。

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_dict中附加了字典countries_dict countries_new_list而不是副本。

您应该在for循环中执行countries_dict = {}或使用副本:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM