0

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}
martineau
  • 119,623
  • 25
  • 170
  • 301
sandbox42
  • 5
  • 2
  • Please share full code. – bereal May 29 '22 at 17:13
  • 2
    Your `return` statement is returning on the first iteration of the loop. Outdent it one level. – BoarGules May 29 '22 at 17:14
  • 1
    ? you are returning after the first iteration of loop, ofc there's only 1 item in the dict – Yamahari May 29 '22 at 17:14
  • Welcome to Stack Overflow. Please carefully note that `print` and `return` have **nothing to do with each other**. The reason the code with `return` only shows one key is that there is only one key in the dict when `return` happens. It is only possible to return once from a given call to the function. Put everything in the dictionary *first*. – Karl Knechtel May 29 '22 at 17:18

1 Answers1

0

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)}
Chris
  • 26,361
  • 5
  • 21
  • 42