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

Sher Meen
  • 3
  • 2
  • you want in result a listwith all these values ? – Devyl Jul 24 '22 at 21:41
  • i need to make a list of all the marks that are stored in temporary variable "k" inside the loop – Sher Meen Jul 24 '22 at 21:41
  • Does this answer your question? [How do I flatten a list of lists/nested lists?](https://stackoverflow.com/questions/20112776/how-do-i-flatten-a-list-of-lists-nested-lists) – SomeDude Jul 24 '22 at 21:47

1 Answers1

2

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)
j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • Thanks, but what if I want to make a list inside the loop? – Sher Meen Jul 24 '22 at 21:44
  • the alternate option doesn't make a list but gives individual values – Sher Meen Jul 24 '22 at 21:48
  • @SherMeen Try running `print(output)` at the end. – j1-lee Jul 24 '22 at 21:49
  • it's giving this output: 20 [20] 40 [20, 40] 50 [20, 40, 50] 33 [20, 40, 50, 33] 45 [20, 40, 50, 33, 45] 38 [20, 40, 50, 33, 45, 38] 24 [20, 40, 50, 33, 45, 38, 24] 50 [20, 40, 50, 33, 45, 38, 24, 50] 50 [20, 40, 50, 33, 45, 38, 24, 50, 50] 43 [20, 40, 50, 33, 45, 38, 24, 50, 50, 43] 44 [20, 40, 50, 33, 45, 38, 24, 50, 50, 43, 44] 39 [20, 40, 50, 33, 45, 38, 24, 50, 50, 43, 44, 39] – Sher Meen Jul 24 '22 at 21:50
  • it's not making a simple list – Sher Meen Jul 24 '22 at 21:51
  • @SherMeen Put `print(output)` __outside__ the for loop (without any indentation), not inside it. – j1-lee Jul 24 '22 at 21:53