Accessing value inside nested dictionaries [duplicate]
I am new to python and need help in solving an issue:
I have a dictionary like
tmpDict = {'ONE':{'TWO':{'THREE':10}}}
Do we have any other way to access THREE's value other than doing
tmpDict['ONE']['TWO']['THREE']
?
Solution 1:
As always in python, there are of course several ways to do it, but there is one obvious way to do it.
tmpdict["ONE"]["TWO"]["THREE"]
is the obvious way to do it.
When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.
If you just want to just save you repetative typing, you can of course alias a subset of the dict:
>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}
Solution 2:
You can use the get() on each dict. Make sure that you have added the None check for each access.