gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:18:48 24 4
gpt4 key购买 nike

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'}]
>>>

关于python - 从元组列表创建字典,输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28808292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com