0

I tried to create a dictionary with nested loops but failed. I do not know what's wrong:

dict={}
for i in range(0,4):
        node_1=str(i)
        for j in range(0,4):
            node_2=str(j)
            dict[node_1]=[node_2]         
print(dict)

It should have created:

{'0':['1','2','3'],'1':['0','2','3'],'2':['0','1','3']}
1
  • 1
    Please format your code as code. It's not readable now Commented Sep 23, 2020 at 11:28

2 Answers 2

2

In your code, you are overwriting the previous j value with the new j value. Instead, you should be appending it to a list.

mydict = {}
for i in range(0,4):
    node_1 = str(i)
    mydict[node_1] = [] # assign empty list
    for j in range(0,4):
        node_2 = str(j)
        mydict[node_1].append(node_2) # append in list

print(mydict)

Output:

{'0': ['0', '1', '2', '3'], '1': ['0', '1', '2', '3'], '2': ['0', '1', '2', '3'], '3': ['0', '1', '2', '3']}

Note: You should not name your variable dict which is the name for a built-in method.

Sign up to request clarification or add additional context in comments.

Comments

1

Something like this?:

d = {}

for i in range(0,4):
        node_1=str(i)
        for j in range(0,4):
            node_2=str(j)
            if node_1 not in d:
                d[node_1] = []
            d[node_1].append(node_2)
print(d)

Please do not use dict for variable name.

Comments

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.