1

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.

3
  • Are you trying to learn about creating nested dictionaries or are you trying to model a chain of nodes in python? Commented Dec 11, 2020 at 17:36
  • Probably the latter? ha Commented Dec 11, 2020 at 18:36
  • Here is the larger problem: stackoverflow.com/questions/65257032/… Commented Dec 11, 2020 at 19:12

2 Answers 2

4
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}}}}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks you for your help!
How would I attach the output to my initial dictionary_name?
dictionary_name = reduce(lambda k, v: {v: k}, reversed(list_name), True)
2
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)

5 Comments

Sorry, I am probably being dense, but when I run the above and print d all I get is {'node10': True} without the nesting.
Yeah sorry I didn't keep a reference to the original dictionary but that should be fixed if you keep a root reference like I added.
Works! Thanks for your help :)
A quick query with regards to your solution. Say for example the entries in list_name are random strings instead of "node1", "node2" etc, how would I go about the same problem?
I moved the keys into a variable. Should be replaceable with random list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.