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)
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)