将嵌套字典转换为csv?

时间:2014-02-22 06:15:27

标签: python csv dictionary indexing

我目前有一个以这种方式格式化的词典:

{state: {region: {place: [name, address]}}}

有许多地区,地方等......编写以这种方式收集信息的程序可能是一个非常糟糕的主意,但现在已经太晚了。有没有人知道我怎么可能开始挖掘这个庞大的字典并把它变成类似的东西:

name, state, region, address,
name, state, region, address,...

甚至

name, state, address,
name, state, address,...

就足够了。我试图让函数像那样对它进行排序让我感到很困惑,它甚至可能吗?

2 个答案:

答案 0 :(得分:0)

我不确定我的数据结构是否正确,但这可能会有所帮助:

>>> data = {"California": {"North": {"San Francisco": ["Bruce Lee", "123 Kickass Drive"], "Berkeley": ["Smokey Bowler", "123 High Street"]}, "South": {"San Diego": ["Juan Valdez", "123 Cafe Blvd."]}}}
>>> data
{'California': {'North': {'San Francisco': ['Bruce Lee', '123 Kickass Drive'], 'Berkeley': ['Smokey Bowler', '123 High Street']}, 'South': {'San Diego': ['Juan Valdez', '123 Cafe Blvd.']}}}
>>> for state, other in data.items():
...   for region, other2 in other.items():
...     for place, info in other2.items():
...         name, address = info
...         print ", ".join([name, state, region, address])
...
Bruce Lee, California, North, 123 Kickass Drive
Smokey Bowler, California, North, 123 High Street
Juan Valdez, California, South, 123 Cafe Blvd.

让它成为一个真正的csv是这个难题的又一步,但我会把它留给你。

答案 1 :(得分:0)

python csv lib中存在一些函数。我没有在下面给出你的案例答案,但只是展示了使用该库的一个例子。

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

每行写一个键/值。你必须适应一个recurvive字典。