I do have a list as given below -
keyList1 = [\"Person\", \"Male\", \"Boy\", \"Student\", \"id_123\", \"Name\"]
value1 = \"Roger\"
How can I ge
You can do this by making nested defaultdict
s:
from collections import defaultdict
def recursive_defaultdict():
return defaultdict(recursive_defaultdict)
def setpath(d, p, k):
if len(p) == 1:
d[p[0]] = k
else:
setpath(d[p[0]], p[1:], k)
mydict = recursive_defaultdict()
setpath(mydict, ["Person", "Male", "Boy", "Student", "id_123", "Name"], 'Roger')
print mydict["Person"]["Male"]["Boy"]["Student"]["id_123"]["Name"]
# prints 'Roger'
This has the nice advantage of being able to write
mydict['a']['b'] = 4
without necessarily having to use the setpath
helper.
You can do it without recursive defaultdict
s too:
def setpath(d, p, k):
if len(p) == 1:
d[p[0]] = k
else:
setpath(d.setdefault(p[0], {}), p[1:], k)