Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python3 returning a dictionary after iteration

so 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

   print(new_dic)

out:

{0: 0}

>Solution :

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)}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading