1. 使用循环创建多个字典:
num_dicts = 5dicts = {}for i in range(num_dicts):new_dict = {'key1': i * 2, 'key2': i * 3}dicts[f'dict_{i}'] = new_dictprint(dicts)
dicts = [{'key1': 1, 'key2': 2},{'key1': 3, 'key2': 4},...]print(dicts)
3. 使用字典嵌套创建多层字典:
a = {}a['testkey'] = a.get('testkey', {})print(a)
4. 使用`collections.defaultdict`创建多层字典:
from collections import defaultdicta = defaultdict(dict)a = {}print(a)

5. 使用字典推导式创建多个字典:
dicts = {i: {j: i * j for j in range(3)} for i in range(3)}print(dicts)
6. 使用` `运算符合并多个字典:
dict1 = {'a': 1, 'b': 2}dict2 = {'b': 3, 'c': 4}dictx = {dict1, dict2}print(dictx)
7. 自定义函数创建多层字典:
def createDict(tupleVals, val):tempName = dictName = {}for index, tupleVal in enumerate(tupleVals):if index == len(tupleVals) - 1:dictName[tupleVal] = valelse:if tupleVal not in dictName.keys():dictName[tupleVal] = {}dictName = dictName[tupleVal]return tempNametupleVals = ('key1', 'key2', 'key3', 'key4', 'key5')dictName = createDict(tupleVals, ['123', '456'])print(dictName['key1']['key2']['key3'])
以上方法可以帮助您根据需要创建多个字典。您可以根据具体需求选择合适的方法
