tags:

views:

529

answers:

2

hi all, I'm currently using the method below to define a multidimensional dictionary in python. Question is... is this the preferred way of defining multidim 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 incement 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
+7  A: 

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'
Federico Ramponi
I recommend this approach, unless you need to pass userdict['site1'] to some function.
gurney alex
I like this idea. This is exactly what tuples are good for because of their immutable nature.
jathanism
This works very well, as long as you don't need to list all the board entries under 'site1'.
Shane Holloway
using this approach I won't be able to do things like..userdict[('site1', 'board1', 'user1', 'pageviews)] += 1
@beagleguy: why not?
Bryan Oakley
got this: KeyError: ('site1', 'board1', 'user1', 'pageviews')
@beagleguy Use `userdict = defaultdict(int)`
Roberto Bonvallet
And you don't need the parentheses: `userdict['site1', 'board1', 'username'] = 'tommy'`.
Roberto Bonvallet
@beagleguy: the value needs to exist before you can add one to it. Once it exists, though, you can increment it with += 1
Bryan Oakley
@Bryan I'm aware the value needs to exist first but if I define the default dict as shown it sets it for me to 0. Just wasn't sure if there was another way to do it.
A: 

This is a pretty subjective question from my perspective. For me, the real question would be at what point do you promote this nested data structure to objects with methods to insulate you from changes. However, I've been known to create large prototyping namespaces with the following:

from collections import defaultdict

def nesteddict(): 
  return defaultdict(nesteddict)
Shane Holloway