I want to have this mydict = {upperkey:{key:value,...},...} and keys[key1, key2, key3...]. In the beginning I created :
mydict = {}
Then:
if upperkey not in mydict:
mydict[upperkey]= dict([(keys[index+1], value)])
else:
mydict[upperkey][keys[index+1]]= value
This way works fine but I find it kind of redundant and using mydict[upperkey]= dict([(keys[index+1], value)]) just not very elegant. However, mydict[upperkey][keys[index+1]] = value doesn’t work unless a dictionary already exists within mydict.
Anyone has a better way to do that?
Use
setdefault: