简体   繁体   中英

How to create dynamic nested dictionaries in Python

I have a list as follows:

list_name=["node1","node2","node3",...,"nodeN"]

I have a dictionary as follows:

dictionary_name:{
  "node1":{
    "node2":true}
   }
}

I would like to set node2 to equal the following:

 "node2"={"node3":{"node4":{...."nodeN"=true}...}}}

I have been unsuccessfully lost in for loops for a while now.

Has anyone got any suggestions?

Thanks in advance.

from functools import reduce

list_name=["node1","node2","node3","nodeN"]
print(reduce(lambda k, v: {v: k}, reversed(list_name), True))

Output:

{'node1': {'node2': {'node3': {'nodeN': True}}}}
root = d = {'node1': {'node2': True}}
n = 10
keys = ["node{}".format(i) for i in range(1, n+1)]
for k in keys[:-1]:
    # Overwrite the True with a dictionary or create a dictionary,
    # not sure the point of the True values in this problem.
    if k not in d or not isinstance(d[k], dict):
        d[k] = {}
    # Recurse into the nested dictionary
    d = d[k]
# Set the final key to True.
d[keys[-1]] = True
print(root)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM