问题
我在for循环的每次迭代中都有单独的字典,但是当第二次迭代运行时,与其将第二个字典添加到第一个字典中,而是将第二个字典替换为第一个字典.
class Nation:
def __init__(self, short_name, long_name, iso_code, iso_short, iso_long, capital):
self.short_name = short_name
self.long_name = long_name
self.iso_code = iso_code
self.iso_short = iso_short
self.iso_long = iso_long
self.capital = capital
def to_dictionaries(z):
a = {}
sD = {}
for i in range(len(z)):
sD["long_name"] = z[i].long_name
sD["iso_code"] = z[i].iso_code
sD["iso_short"] = z[i].iso_short
sD["iso_long"] = z[i].iso_long
sD["capital"] = z[i].capital
a.update(sD)
return a
new_nation_1 = Nation("Albania", "Republic of Albania", 8, "AL", "ALB", "Tirana")
new_nation_2 = Nation("Angola", "Republic of Angola", 24, "AO", "AGO", "Luanda")
nation_list = [new_nation_1, new_nation_2]
print(to_dictionaries(nation_list))
所需的输出:
{"Albania": {"long_name": "Republic of Albania", "iso_code": 8, "iso_short": "AL", "iso_long": "ALB", "capital": "Tirana"},
"Angola": {"long_name": "Republic of Angola", "iso_code": 24, "iso_short": "AO", "iso_long": "AGO", "capital": "Luanda"}}
实际输出:
{'long_name': 'Republic of Angola', 'iso_code': 24, 'iso_short': 'AO', 'iso_long': 'AGO', 'capital': 'Luanda'}
我该如何解决这个问题?