带列表的嵌套Dicts

时间:2015-04-03 13:20:10

标签: python list dictionary

我想构建一个带有列表作为值的dict,其中包含带有列表作为值的词:

xml_dict = { 
'Spain':['La Palma':[2929, ..], 'Fuerteventura':[5733, ..]],
'Turkey':['Antalya':[16483, ..], 'Izmir':[2927, ...]] 
... }

我的出发基础是一个带有dicts的列表:

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_abweichungxml_dict(self.db_data_list)的值。我不知道如何管理它。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我认为你真正需要的是一个字典作为值的字典,其中那些内部字典将列表作为值。

for hotel in self.db_data_list:
    land = hotel['land']
    town = hotel['zielgebiet_abweichung']
    code = hotel['giatahotelcode']
    if land in all_data:
        if town in all_data[land]:
            all_data[land][town].append(code)
        else:
            all_data[land][town] = [code]
    else:
        all_data[land] = {town: [code]}

返回:

{'Turkey': {'Antalya': [16483], 'Izmir': [2927]}, 
 'Spain': {'Fuerteventura': [5733], 'La Palma': [2929]}}

您也可以使用setdefault执行相同的操作:

all_data = {}
for hotel in self.db_data_list:
    land = all_data.setdefault(hotel['land'], {})
    town = land.setdefault(hotel['zielgebiet_abweichung'], [])
    town.append(hotel['giatahotelcode'])