-2

我通过更合乎逻辑的方式更改最终结构:

{'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)

我还是实现代码@Eric

4

1 回答 1

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()
于 2012-11-18T16:47:57.430 回答