0

I currently have a dictionary that's formatted in this way:

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

There are a lot of regions, places, etc... it was probably a really bad idea to write a program that collects information in that manner, but it's too late now. Does anyone have an idea how I could possible start digging through this huge dictionary and turn it into something like:

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

Even

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

would be enough. I'm getting way too confused trying to make a function to sort it like that, is it even possible?

Howcan
  • 313
  • 3
  • 5
  • 16

2 Answers2

0

I am not sure I have your data structure correct, but maybe this will help:

>>> 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.

Making it a true csv is one more step in the puzzle, but I will leave that one to you.

sberry
  • 128,281
  • 18
  • 138
  • 165
0

Some functions exist in the python csv lib. I am not giving answer to your case below, but just showing an example of use of the library.

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())

will write one key/value per line. You must adapt to a recurvive dictionary.

kiriloff
  • 25,609
  • 37
  • 148
  • 229