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}}}
Answer from ch3ka on Stack OverflowAs 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}}}
My implementation:
def get_nested(data, *args):
if args and data:
element = args[0]
if element:
value = data.get(element)
return value if len(args) == 1 else get_nested(value, *args[1:])
Example usage:
>>> dct={"foo":{"bar":{"one":1, "two":2}, "misc":[1,2,3]}, "foo2":123}
>>> get_nested(dct, "foo", "bar", "one")
1
>>> get_nested(dct, "foo", "bar", "two")
2
>>> get_nested(dct, "foo", "misc")
[1, 2, 3]
>>> get_nested(dct, "foo", "missing")
>>>
There are no exceptions raised in case a key is missing, None value is returned in that case.
How to access nested dictionary and set value in it.
Using get() with nested dictionary.
How to get value inside nested dictionary
How to walk through a nested dictionary with it's keys in a list?
Videos
I have a class which have dict_var. From another file I want to access this dict_var by using class methods. To retrieve value I have a class methods which takes *args and return correct value (look at the code). My question is how to set new value? is there any pointer like things in python? or set value directly to `id()` of a object. Thanks in advance.
dict_var={
"a":{
"b":{
"c":0
},
"d":{
"e":{
"f":0
}
}
},
"x":12
}
#i can retrieve the value using for loop.
def get_nested_value(dict_obj, *args):
"""Return value from inside a nested dictionary"""
temp = dict_obj
for key in args:
temp = temp[key]
return temp
print(get_nested_value(dict_var,'a','b','c')) #0