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

I need to make a list of multiple values stored in an temporary variable in a loop

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

>Solution :

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

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)
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