Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 322
Gana Avatar asked May 01 '12 15:05

Gana


People also ask

How do I access nested dict values?

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 ).

Are duplicate values allowed in dictionary?

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.

How do you check if a value is in a nested dictionary Python?

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.

Do dictionaries allow duplicate keys?

The Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.


1 Answers

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}}} 
like image 168
ch3ka Avatar answered Sep 28 '22 18:09

ch3ka