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

标签 python data-structures dictionary

我目前正在使用下面的方法在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)

得到以下结构:

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

我还使用它为用户动态增加计数器,而无需检查键是否存在或是否已设置为 0。例如:

userdict['site1']['board1']['username']['pageviews'] += 1

最佳答案

元组是可散列的。可能我错过了重点,但你为什么不使用标准字典,约定键是三元组呢?例如:

userdict = {}
userdict[('site1', 'board1', 'username')] = 'tommy'

关于python - 在python中定义多维字典的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2388302/

相关文章:

java - 困惑 - 二叉树的高度

objective-c - 有没有办法将对象映射到基元?

python - 如何将zlib数据插入Mongo? (统一码问题)

python - scipy.interpolate.griddata : cut z-value and get area inside it

data-structures - 如何实现递归deftype

python - 如何在多个进程之间共享字典?

python - 使用字典的最短路径算法[Python]

python - 如何将 turtle 移动到 Canvas 的边缘?

javascript - 使用 Selenium 从 Javascript 网页派生文本

java - 具有2个值字段的自定义 HashMap VS在java中实现以数组作为值的 HashMap