I have following function where I build dict of dicts dynamically (here DoD is created statically for simplicity):
import json
def fun(dummyArg1, dummyArg2):
DoD = {'a': {'aa':1, 'ab':2}, 'b': {'ba':3, 'bb':4}, 'c': '5'}
print json.dumps(DoD, sort_keys=True, indent=4)
# FURTHER CODE THAT WILL WORK WITH DoD VARIABLE GOES HERE
In [1]: fun(1,2)
Out[1]:
{
"a": {
"aa": 1,
"ab": 2
},
"b": {
"ba": 3,
"bb": 4
},
"c": "5"
}
Is it possible to specify particular DoD
element content during function call? I would like to have something like:
fun(dummyArg1, dummyArg2, DoD["b"]["ba"] = "New Value")
I know that it is possible e.g. via passing list where 0th position is new value, 1st position is "outer" dict key and 2nd position is "inner" dict key:
import json
lst = ["New Value", "b", "ba"]
def fun(arg1, arg2, additionalParams):
DoD = {'a': {'aa':1, 'ab':2}, 'b': {'ba':3, 'bb':4}, 'c': '5'}
DoD[additionalParams[1]][additionalParams[2]] = additionalParams[0]
print json.dumps(DoD, sort_keys=True, indent=4)
# FURTHER CODE THAT WILL WORK WITH DoD VARIABLE GOES HERE
In [1]: fun(1,2,lst)
Out[1]:
{
"a": {
"aa": 1,
"ab": 2
},
"b": {
"ba": "New Value",
"bb": 4
},
"c": "5"
}
But as you can see it is not very robust (changing value under key 'c'
requires rewriting the function code) nor elegant. Is there better approach?
Bonus question: Why in last example after assignment "ba"
contains ["New Value"]
instead of "New Value"
?
PS: Even if DoD
will be created dynamically there will always be DoD["b"]["ba"]
element.