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(nation_list):
my_dictionary_1 = {}
my_dictionary_2 = {}
my_dictionary_3 = {}
for i in [nation_list]:
my_dictionary_1 = nation_list.short_name
for j in [nation_list]:
my_dictionary_2["long_name"] = nation_list.long_name
my_dictionary_2["iso_code"] = nation_list.iso_code
my_dictionary_2["iso_short"] = nation_list.iso_short
my_dictionary_2["iso_long"] = nation_list.iso_long
my_dictionary_2["capital"] = nation_list.capital
my_dictionary_3[my_dictionary_1] = my_dictionary_2
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': 24, 'iso_short': 'AO', 'iso_long': 'AGO', 'capital': 'Luanda'}, 'Angola': {'long_name': 'Republic of Angola', 'iso_code': 24, 'iso_short': 'AO', 'iso_long': 'AGO', 'capital': 'Luanda'}}
答案 0 :(得分:0)
nation_list
是一个列表对象。由于您要遍历列表,因此请使用i.short_name
。您也可以使用dict.setdefault
和dict.update
例如:
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(nation_list):
result = {}
for i in nation_list:
result.setdefault(i.short_name, {}).update({"long_name": i.long_name, "iso_code": i.iso_code, "iso_short": i.iso_short, "iso_long": i.iso_long, "capital": i.capital})
return result
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': {'capital': 'Tirana',
'iso_code': 8,
'iso_long': 'ALB',
'iso_short': 'AL',
'long_name': 'Republic of Albania'},
'Angola': {'capital': 'Luanda',
'iso_code': 24,
'iso_long': 'AGO',
'iso_short': 'AO',
'long_name': 'Republic of Angola'}}