1. 使用普通字典:
nested_dict = {}nested_dict['level1'] = {}nested_dict['level1']['level2'] = {}
2. 使用`defaultdict`:
from collections import defaultdictfamCountDictofDicts = {"one": {"oneA": 1, "oneB": 2, "oneC": 3},"two": {}}
3. 通过循环动态创建嵌套字典:

def stud(data):empty_dic = {}for line in data:empty_dic[line["stud_num"]] = {line["course"]: line["marks"]}return empty_dic
4. 从文件中读取数据创建嵌套字典:
tdict = {}with open('f1') as f:while True:line = f.readline().strip()if not line:breakpos1 = line.split()pos2 = line.split()pos3 = line.split()if pos1 not in tdict:tdict[pos1] = {}if pos2 not in tdict[pos1]:tdict[pos1][pos2] = []tdict[pos1][pos2].append(pos3)tdict = {"A": {1: ["a", "b"], 2: ["C"]},"B": {2: ["a", "b"]}}
5. 使用列表来嵌套字典:
aliens = [{"color": "green", "speed": 10, "IQ": 0},{"color": "green", "speed": 10, "IQ": 0},{"color": "green", "speed": 10, "IQ": 0}]for alien in aliens:print(alien)
以上示例展示了如何在Python中创建嵌套字典的不同方法。您可以根据具体需求选择合适的方法
