The default Dict method defines a multidimensional dictionary in Python is more complex
And not directly through
A=dict () a[' B ' [' C '] [' d '] = 1>>> a[' b ' [' C '] [' d ']=1traceback (most recent call last): File "<stdin>", line 1, in <module>keyerror: ' B '
If you want to create a multidimensional dictionary, you need to do this
>>> a={}>>>>>> a[' b '] = {}>>> a[' b ' [' C ']={}>>> a[' b ' [' C '] [' d '] = 1> >> a{' B ': {' c ': {' d ': 1}}}
More cumbersome
There are 4 ways to create a multidimensional dictionary:
First Kind
From collections Import Defaultdictdef site_struct (): Return Defaultdict (board_struct) def board_struct (): Return def Aultdict (user_struct) def user_struct (): Return Dict (pageviews=0,username= ", comments=0) userdict = Defaultdict (site_ struct) userdict[' site ' [' board '] [' username '] = 1userdict[' par ' [' CHL '] [' username '] = ' ceshi ' Print userdict[' site ' [ ' board ' [' username ']print userdict[' par ' [' CHL '] [' username ']
Using the characteristics of the Collections module Defaultdict method, the external function is used to realize
The second Kind
UserDict = {}userdict[(' site1 ', ' board1 ', ' username ')] = ' Tommy '
Using tuples to act as a key to a multidimensional dictionary, the multidimensional key is placed in a tuple as a rule, using that tuple as the key of the dictionary and assigning values to achieve the effect of multidimensional key
Third Kind
From collections import Defaultdictfrom collections import Counterdef multi_dimensions (n, type): if N<=1:return t Ype () return defaultdict (Lambda:multi_dimensions (n-1, type)) m = multi_dimensions (5, Counter) m[' D1 ' [' D2 '] [' D3 '] [' D4 ' ] = 1>>> mdefaultdict (<function <lambda> at 0x322c70>, {' D1 ': defaultdict (<function <lambda& Gt at 0x322870> {' D2 ': defaultdict (<function <lambda> at 0x322cf0>, {' D3 ': Defaultdict (<function < Lambda> at 0x322d30>, {' D4 ': 1})})})
This approach is more like an iterator that iterates over the creation
Fourth type
From collections Import Defaultdictdef nesteddict (): Return Defaultdict (nesteddict) >>> c[' key1 ' [' Key2 '] [' Ke Y3 '] = 10>>> cdefaultdict (<function nesteddict at 0x322cf0>, {' Key1 ': defaultdict (<function Nesteddict at 0x322cf0> {' Key2 ': defaultdict (<function nesteddict at 0x322cf0>, {' Key3 ': 10})})
Essentially, this approach is an iterator
This article from "Tring" blog, reproduced please contact the author!
Python defines multidimensional dictionaries