2012-11-18 28 views
-2

我一個更合乎邏輯的改變最終結構:更Python的方法如下算法

{'state1': {'city1': ['dict1', 'dict2']}, 'state2': {'City2': ['dict3']}} 

,代碼:

dir_dict = {} 
for one in objects: 
    state = one.dir.city.state.name 
    city ​​= one.dir.city.name 
    address = one.dir.address 
    if state not in dir_dict: 
     dir_dict[state] = {} 
    if city not in dir_dict[state]: 
     dir_dict[state][city] = [] 
    dir_dict[state][city].append(address) 

我仍然執行代碼@埃裏克

+4

你能展示一些樣本輸入和輸出嗎? – Eric

+1

你爲什麼要設置'dir_dict [x.direction.city.state.name]'兩次? –

+0

@Inbar:設置它,然後「唯一化」它。看起來合理,如果有點冗長。 – Eric

回答

0
from collections import defaultdict 
dir_dict = defaultdict(lambda: defaultdict(set)) 
for x in objects: 
    dir_dict[x.state][x.city].add(x.address) 

dir_list = dir_dict.keys()