欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python创建多维字典方法

程序员文章站 2022-07-02 12:30:26
python不直接创建多维字典,需要逐层判断不存在创建,存在追加: 例如: 不能直接 dictName['key1']['key2']['key3']['key4']['key5'] = ['123', '456'] 下面函数实现: def createDict(tupleVals, val): t ......

python不直接创建多维字典,需要逐层判断不存在创建,存在追加:

例如:

不能直接

dictname['key1']['key2']['key3']['key4']['key5'] = ['123', '456']

 

下面函数实现:

def createdict(tuplevals, val):
tupnum = len(tuplevals)
tempname = dictname = {}
for index, tupleval in enumerate(tuplevals):
if index == tupnum - 1:
dictname[tupleval] = val
else:
if tupleval not in dictname.keys():
dictname[tupleval] = {}
else:
dictname.update({tupleval: {}})
dictname = dictname[tupleval]
return tempname

dictname = createdict(('key1', 'key2', 'key3', 'key4', 'key5'), ['123', '456'])
print(dictname['key1']['key2']['key3'])