I have a data structure which essentially amounts to a nested dictionary. Let\'s say it looks like this:
{\'new jersey\': {\'mercer county\': {\'plumbers\':
For easy iterating over your nested dictionary, why not just write a simple generator?
def each_job(my_dict):
for state, a in my_dict.items():
for county, b in a.items():
for job, value in b.items():
yield {
'state' : state,
'county' : county,
'job' : job,
'value' : value
}
So then, if you have your compilicated nested dictionary, iterating over it becomes simple:
for r in each_job(my_dict):
print "There are %d %s in %s, %s" % (r['value'], r['job'], r['county'], r['state'])
Obviously your generator can yield whatever format of data is useful to you.
Why are you using try catch blocks to read the tree? It's easy enough (and probably safer) to query whether a key exists in a dict before trying to retrieve it. A function using guard clauses might look like this:
if not my_dict.has_key('new jersey'):
return False
nj_dict = my_dict['new jersey']
...
Or, a perhaps somewhat verbose method, is to use the get method:
value = my_dict.get('new jersey', {}).get('middlesex county', {}).get('salesmen', 0)
But for a somewhat more succinct way, you might want to look at using a collections.defaultdict, which is part of the standard library since python 2.5.
import collections
def state_struct(): return collections.defaultdict(county_struct)
def county_struct(): return collections.defaultdict(job_struct)
def job_struct(): return 0
my_dict = collections.defaultdict(state_struct)
print my_dict['new jersey']['middlesex county']['salesmen']
I'm making assumptions about the meaning of your data structure here, but it should be easy to adjust for what you actually want to do.