Question:
For a dictionary dicc_n
that contains the names of n students as keys and a list with the notes of type float as values, in addition to that, then print the average of those notes, I would like the dictionary to appear as follows when printing:
Notes: 'name' -> notes -> average
and not:
{'nombre':[[notas],[promedio]]}
Example: {'Juan':[[5,4,5,3],[4.25]],'Marcos':[[4.0,5.0],[4.5]]}
Expected result after printing:
Grades:
Juan -> 5 , 4 , 5, 3 -> Average = 4.25
Frames -> 4.0 , 5.0 -> Average = 4.5
Answer:
Having a dictionary like this:
dic = {'Juan':[[5,4,5,3],[4.25]],'Marcos':[[4.0,5.0],[4.5]]}
The only thing we have to do is go through it to access each of its elements, this is done with a for loop
for name in dic.keys():
#convertimos cada elemento a string
notas = [str(n) for n in dic[name][0]]
prom = [str(n) for n in dic[name][1]]
#imprimimos
print(f"{name} -> {','.join(notas)} Promedio = {','.join(prom)}")
when printing we make use of a list compression and the .join()
method, the list compression is the same as a for
loop, in that case we go through the list and convert each element to a string, so that when using .join()
let's have no problems. What the ",".join()
method does is join the elements of the list according to the character that we pass to it, in this case ,
, having as a result.
Juan -> 5,4,5,3 Promedio = 4.25
Marcos -> 4.0,5.0 Promedio = 4.5