Returning a dictionary after iteration

Question:

I have my dictionary iterating over my integer array the way I want and get my desired result with print but only get the first iteration when I use a return statement

for i in range(0, N):
    new_dic.update({i:Vk_s[i]})
    print(new_dic)

out:

{0: 0}
{0: 0, 1: 0}
{0: 0, 1: 0, 2: 0}
{0: 0, 1: 0, 2: 0, 3: 4}
{0: 0, 1: 0, 2: 0, 3: 4, 4: 5}
{0: 0, 1: 0, 2: 0, 3: 4, 4: 5, 5: 6}

vs

for i in range(0, N):
     new_dic.update({i:Vk_s[i]})
     return(new_dic)

print(new_dic)

out:

{0: 0}
Asked By: sandbox42

||

Answers:

First, it appears your indentation is off. You return after a single iteration of the loop:

for i in range(0, N):
   new_dic.update({i:Vk_s[i]})
   return(new_dic)

Assuming this is the body of a function, you may want:

for i in range(0, n):
    new_dic.update({i: Vk_s[i]})

return new_dic

Secondly, are you certain you don’t want a dictionary comprehension?

{i: Vk_s[i] for i in range(0, N)}
Answered By: Chris
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.