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

Time:01-30

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:

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

CodePudding user response:

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

CodePudding user response:

Just use a single for loop. In each iteration of your inner loop you overwrite the value of Example[Multiple]. So since the last value of Results is 25, all of your values end up as 25. Try this:

for i in range(0, len(Results)):
    Example[Multiples[i]] = Results[i]
  •  Tags:  
  • Related