1. 定义多级字典
from collections import defaultdict
recur_dict = lambda: defaultdict(recur_dict)
data = recur_dict()
data["hello"] ="world"
data["good"]["day"] = True
2. defaultdict转化为dict
# 方式一:
import json
print(json.loads(json.dumps(data)))
# 方式二:
from collections import defaultdict
def ddict():
return defaultdict(ddict)
def ddict2dict(d):
for k, v in d.items():
if isinstance(v, dict):
d[k] = ddict2dict(v)
return dict(d)
myddict = ddict()
myddict["a"]["b"]["c"] ="value"
print(myddict)
mydict = ddict2dict(myddict)
print(mydict)
3. 参考