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

例如:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

不能直接

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'])

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄