lal*_*rde 4 python dictionary python-2.7
要声明一个空字典,我这样做:
mydict = dict()
Run Code Online (Sandbox Code Playgroud)
要声明一个空字典的空字典,我也可以这样做:
mydictofdict = dict()
Run Code Online (Sandbox Code Playgroud)
然后在需要时添加字典:
mydict1 = dict()
mydictofdict.update({1:mydict1})
Run Code Online (Sandbox Code Playgroud)
以及需要时其中的元素:
mydictofdict[1].update({'mykey1':'myval1'})
Run Code Online (Sandbox Code Playgroud)
它是pythonic吗?有没有更好的方法来执行它?
您可以将collections.defaultdict用于嵌套字典,您可以在其中定义字典的初始值
from collections import defaultdict
#Use the initial value as a dictionary
dct = defaultdict(dict)
dct['a']['b'] = 'c'
dct['d']['e'] = 'f'
print(dct)
Run Code Online (Sandbox Code Playgroud)
输出将是
defaultdict(<class 'dict'>, {'a': {'b': 'c'}, 'd': {'e': 'f'}})
Run Code Online (Sandbox Code Playgroud)