在python中定义多维字典的最佳方法?

Jam*_*mes 29 python dictionary data-structures

我目前正在使用下面的方法在python中定义一个多维字典.我的问题是:这是定义多维决策的首选方式吗?

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)
Run Code Online (Sandbox Code Playgroud)

获得以下结构:

userdict['site1']['board1']['username'] = 'tommy'
Run Code Online (Sandbox Code Playgroud)

我也使用它来为用户动态增加计数器,而不必检查密钥是否存在或已经设置为0.例如:

userdict['site1']['board1']['username']['pageviews'] += 1
Run Code Online (Sandbox Code Playgroud)

Fed*_*oni 45

元组是可以清洗的.可能我错过了这一点,但是你为什么不使用一个标准的字典,其中的键将是三元组的约定?例如:

userdict = {}
userdict[('site1', 'board1', 'username')] = 'tommy'
Run Code Online (Sandbox Code Playgroud)

  • 您不能使用元组方法迭代单个维度. (8认同)
  • 你不需要括号:`userdict ['site1','board1','username'] ='tommy'`. (3认同)
  • 这很有效,只要您不需要列出'site1'下的所有电路板条目. (2认同)

and*_*vom 16

您可以创建任何类型的多维字典,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)