Array of dict or lists or ....?

Scott David Daniels Scott.Daniels at Acm.Org
Wed Oct 8 23:28:07 EDT 2008


Pat wrote:
> I can't figure out how to set up a Python data structure to read in data 
> that looks something like this (albeit somewhat simplified and contrived):
> 
> States
>    Counties
>      Schools
>        Classes
>           Max Allowed Students
>           Current enrolled Students
> 
> Nebraska, Wabash, Newville, Math, 20, 0
> Nebraska, Wabash, Newville, Gym, 400, 0
> Nebraska, Tingo,  Newfille, Gym, 400, 0
> Ohio, Dinger, OldSchool, English, 10, 0
> 
> With each line I read in, I would create a hash entry and increment the 
> number of enrolled students.


You might want something like this:

 >>> import collections, functools
 >>> int_dict = functools.partial(collections.defaultdict, int)
 >>> curr = functools.partial(collections.defaultdict, int)
 >>> # builds a dict-maker where t = curr(); t['name'] += 1  "works"
 >>> for depth in range(4):
         # add a layer with a default of the preceding "type"
	curr = functools.partial(collections.defaultdict, curr)
 >>> base = curr() # actually make one
 >>> base['Nebraska']['Wabash']['Newville']['Math']['max'] = 20
 >>> base['Nebraska']['Wabash']['Newville']['Math']['curr'] += 1
 >>> base['Nebraska']['Wabash']['Newville']['Math']['curr']
   1
 >>> base['Nebraska']['Wabash']['Newville']['English']['curr']
   0


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list