我想建立列表作爲值,其中包含類型的字典與列表爲值的字典:使用列表嵌套日文N3 N4 N5
xml_dict = {
'Spain':['La Palma':[2929, ..], 'Fuerteventura':[5733, ..]],
'Turkey':['Antalya':[16483, ..], 'Izmir':[2927, ...]]
... }
我的出發基礎是有類型的字典列表:
self.db_data_list = [
{'land': 'Spain', 'giatahotelcode': 2929, 'zielgebiet_abweichung': 'La Palma'},
{'land': 'Spain', 'giatahotelcode': 5733, 'zielgebiet_abweichung': 'Fuerteventura'},
{'land': 'Turkey', 'giatahotelcode': 16483, 'zielgebiet_abweichung': 'Antalya'},
{'land': 'Turkey', 'giatahotelcode': 2927, 'zielgebiet_abweichung': 'Izmir'}
而且這是我到目前爲止的代碼:
zg_giata_dict = dict()
country_zg_dict = dict()
xml_dict = dict()
countries = [ value for data_dict in self.db_data_list for key, value in data_dict.iteritems() if key == 'land' ]
countries = set(countries)
zgs = [ value for data_dict in self.db_data_list for key, value in data_dict.iteritems() if key == 'zielgebiet_abweichung' ]
zgs = set(zgs)
for data_dict in self.db_data_list:
for country in countries:
if data_dict['land'] == country:
country_zg_dict.setdefault(country, []).append(data_dict['zielgebiet_abweichung'])
country_zg_dict[country] = list(set(country_zg_dict[country]))
for data_dict in self.db_data_list:
for zg in zgs:
if data_dict['zielgebiet_abweichung'] == zg:
zg_giata_dict.setdefault(zg, []).append(data_dict['giatahotelcode'])
for country, zg_list in country_zg_dict.iteritems():
for zg, giata_list in zg_giata_dict.iteritems():
if zg in zg_list:
xml_dict.setdefault(country, []).append(giata_list)
輸出xml_dict:
{'Spain': [[2929, ...], [5733, ...]], 'Turkey': [[16483, ...], [2927, ...]], ... }
我的輸出結果並不差 - 但我錯過了zielgebiet_abweichung
(self.db_data_list)在我的xml_dict
中的值。我不知道如何管理它。有任何想法嗎?
你想要的輸出 - '{ '西班牙':'拉帕爾馬':[2929,..],'Fuerteventura':[5733,..]], 'Turkey':['Antalya':[16483,..],'Izmir':[2927,...]] ...}' - 不是有效的字典或列表 – Stuart 2015-04-03 13:33:32
Sorr y',我的錯:'xml_dict ='Spain':[{'La Palma':[2929,..}],'Fuerteventura':[{5733,..]}], '土耳其':[{ '安塔利亞':[16483,..],'伊茲密爾':[2927,...]}] ...}' – jwi 2015-04-03 13:37:55
不,那也行不通。不想要你想要的只是一個嵌套字典,如'{'西班牙':{'拉帕爾馬':[2929,...],'富埃特文圖':[5733,...]},'土耳其':{ 'Antalya':[16483,...],'Izmir':[2927,...]}}' – Stuart 2015-04-03 13:43:46