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

How can i do a double for loop and save it in a dictionary?

Hi i’m trying to do a double for loop an save it in a dict. The code that i’m using is:

Results = 5, 10, 15, 20, 25
Multiples = ['Multiples1','Multiples2','Multiples3','Multiples4','Multiples5']

Example = {}
for Multiple in Multiples:
    for i in range(0,len(Results)):
        Example[Multiple] = Results[i]

I want that in "Example" each multiple go with the respective number like this:

{'Multiples1':5, 
'Multiples2':10, 
'Multiples3':15,
'Multiples4':20,
'Multiples5':25} 

but the result that i get form this code is:

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

{'Multiples1': 25,
 'Multiples2': 25,
 'Multiples3': 25,
 'Multiples4': 25,
 'Multiples5': 25}

>Solution :

You can use a single for loop:

for i in range(len(Results)):
    Example[Multiples[i]] = Results[i]

Since your expected output is like this…

{
    'Multiples1':5, 
    'Multiples2':10,
    ...
}

…you can try a solution that doesn’t involve the Multiples iterable:

for i in range(len(Results)):
    Example[f"Multiple{i}"] = Results[i]

You should be aware about how iterables are assigned in Python:

Results = 5, 10, 15, 20, 25 #This won't work
Results = [5, 10, 15, 20, 25] #This will work, and is a list
Results = {5, 10, 15, 20, 25} #This will work, and is a set
Results = (5, 10, 15, 20, 25) #This will work, and is a tuple
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