python中如何生成嵌套字典

1.用defaultdict
from collections import defaultdict
#如果想生成一個嵌套的dict,如何處理,python3可以,python2貌似不可以
def gen_dict():
    return {
        'name': '',
        'num': 0,
    }
d_dict = defaultdict(gen_dict)
d_dict['group1']

2.用setdefault

# 生成嵌套dict {1: {‘errors’: {0: ‘d:/helloworld’, 1: ‘d:/dict’}, ‘os’: ‘windows’, ‘type’: 2}}
d = {}
d1 = d.setdefault(1, {})
d2 = d1.setdefault('errors', {})
d1.setdefault('os', 'windows')
d1.setdefault('type', 2)
d2.setdefault(0, 'd:/helloworld')
d2.setdefault(1, 'd:/dict')
print d

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章