在python中默认的dict方法定义多维字典较为复杂
并不能直接通过
a=dict()
a['b']['c']['d'] = 1
>>> a['b']['c']['d']=1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'b'
如果想要创建多维字典,需要这样做
>>> a={}
>>>
>>> a['b'] = {}
>>> a['b']['c']={}
>>> a['b']['c']['d'] = 1
>>> a
{'b': {'c': {'d': 1}}}
比较繁琐
比较推荐的创建多维字典的方法有4种:
第一种
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['site']['board']['username'] = 1
userdict['par']['chl']['username'] = 'ceshi'
print userdict['site']['board']['username']
print userdict['par']['chl']['username']
利用collections模块defaultdict方法的特性,利用外部函数来实现
第二种
userdict = {}
userdict[('site1', 'board1', 'username')] = 'tommy'
利用元组来充当多维字典的key,即将多维key按照规则放入元组中,使用该元组作为字典的key并赋值,以达到多维key的效果
第三种
from collections import defaultdict
from collections import Counter
def multi_dimensions(n, type):
if n<=1:
return type()
return defaultdict(lambda:multi_dimensions(n-1, type))
m = multi_dimensions(5, Counter)
m['d1']['d2']['d3']['d4'] = 1
>>> m
defaultdict(<function <lambda> at 0x322c70>, {'d1': defaultdict(<function <lambda> at 0x322870>, {'d2': defaultdict(<function <lambda> at 0x322cf0>, {'d3': defaultdict(<function <lambda> at 0x322d30>, {'d4': 1})})})})
这种方法更像是一个迭代器,迭代创建
第四种
from collections import defaultdict
def nesteddict():
return defaultdict(nesteddict)
>>> c['key1']['key2']['key3'] = 10
>>> c
defaultdict(<function nesteddict at 0x322cf0>, {'key1': defaultdict(<function nesteddict at 0x322cf0>, {'key2': defaultdict(<function nesteddict at 0x322cf0>, {'key3': 10})})})
这种方法从根本上讲,就是一个迭代器