Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For easy iterating over your nested dictionary, why not just write a simple generator?</p> <pre><code>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 } </code></pre> <p>So then, if you have your compilicated nested dictionary, iterating over it becomes simple:</p> <pre><code>for r in each_job(my_dict): print "There are %d %s in %s, %s" % (r['value'], r['job'], r['county'], r['state']) </code></pre> <p>Obviously your generator can yield whatever format of data is useful to you.</p> <p>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:</p> <pre><code>if not my_dict.has_key('new jersey'): return False nj_dict = my_dict['new jersey'] ... </code></pre> <p>Or, a perhaps somewhat verbose method, is to use the get method:</p> <pre><code>value = my_dict.get('new jersey', {}).get('middlesex county', {}).get('salesmen', 0) </code></pre> <p>But for a somewhat more succinct way, you might want to look at using a <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow noreferrer">collections.defaultdict</a>, which is part of the standard library since python 2.5.</p> <pre><code>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'] </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload