Home > Software design >  I need to make a list of multiple values stored in an temporary variable in a loop
I need to make a list of multiple values stored in an temporary variable in a loop

Time:07-25

marks={"Farah":[20,40,50,33],"Ali":[45,38,24,50],"Sarah":[50,43,44,39]}
print(" " ,list(marks.keys()) , "-\n", list(marks.values()))

for key,value in marks.items():
    for j in marks.values():
        for k in (j):
            print(k)

This is my code and i need to make the list of all variables stored in k that are 20,40,50,33,45,38,24,50,50,43,44,39

CodePudding user response:

You can use itertools.chain:

from itertools import chain

marks={"Farah":[20,40,50,33],"Ali":[45,38,24,50],"Sarah":[50,43,44,39]}

output = list(chain(*marks.values()))
print(output) # [20, 40, 50, 33, 45, 38, 24, 50, 50, 43, 44, 39]

Note that, on python version below 3.7, the order in the list might be different.

Alternatively, if you need a for loop (e.g., because you are doing some other operations) and need to store the temporary values, then you can make an empty list first and then append the value to the list at each iteration:

output = []
for val_list in marks.values():
    for v in val_list:
        print(v)
        output.append(v)

print(output)
  • Related