Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to define multidimensional dictionaries in python? [duplicate]

I'm currently using the method below to define a multidimensional dictionary in python. My question is: Is this the preferred way of defining multidimensional dicts?

from collections import defaultdict  def site_struct():      return defaultdict(board_struct)  def board_struct():      return defaultdict(user_struct)  def user_struct():      return dict(pageviews=0,username='',comments=0)  userdict = defaultdict(site_struct) 

to get the following structure:

userdict['site1']['board1']['username'] = 'tommy' 

I'm also using this to increment counters on the fly for a user without having to check if a key exists or is set to 0 already. E.g.:

userdict['site1']['board1']['username']['pageviews'] += 1 
like image 604
James Avatar asked Mar 05 '10 16:03

James


2 Answers

Tuples are hashable. Probably I'm missing the point, but why don't you use a standard dictionary with the convention that the keys will be triples? For example:

userdict = {} userdict[('site1', 'board1', 'username')] = 'tommy' 
like image 87
Federico A. Ramponi Avatar answered Sep 20 '22 04:09

Federico A. Ramponi


You can create a multidimensional dictionary of any type like this:

from collections import defaultdict from collections import Counter  def multi_dimensions(n, type):   """ Creates an n-dimension dictionary where the n-th dimension is of type 'type'   """     if n<=1:     return type()   return defaultdict(lambda:multi_dimensions(n-1, type))  >>> m = multi_dimensions(5, Counter) >>> m['d1']['d2']['d3']['d4'] Counter() 
like image 27
andersonvom Avatar answered Sep 23 '22 04:09

andersonvom