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']
?
Access Values using get() Another way to access value(s) in a nested dictionary ( employees ) is to use the dict. get() method. This method returns the value for a specified key. If the specified key does not exist, the get() method returns None (preventing a KeyError ).
If you want to keep duplicate keys in a dictionary, you have two or more different values that you want to associate with same key in dictionary. The dictionary can not have the same keys, but we can achieve a similar effect by keeping multiple values for a key in the dictionary.
Use get() and Key to Check if Value Exists in a Dictionary Dictionaries in Python have a built-in function key() , which returns the value of the given key. At the same time, it would return None if it doesn't exist.
The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
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}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With