Returning Added Data in a Dictionary

Asked

Viewed 82 times

1

In my code I am asking the user to enter the note, n° of registration and frequency of 2 people.

But I want to do this using dictionaries, so I declared the keys 'Nota', 'Matricula' and 'Freqüência' and stored in the variable aluno. But when it comes time to display the data of these two students using the method items() i can access only the data of 1° student or the data of 2° student, never the two together.

My question is how to display the two data of student A and student B using the dictionaries.

aluno = dict()

lista = []

for i in range(2):

    aluno['Nota'] = int(input(f'Digite o nota do aluno {i+1}: '))

    aluno['Matricula'] = int(input(f'Digite o numero da matricula: '))

    aluno['Frequencia'] = int(input('Digite a frequencia em porcentagem: '))

    print('--------------------------------------------')

    lista.append(aluno.copy())


for k,v in lista[1].items():

    print(k,':',  v,)
  • Hello @Giovanni, I see that a solution proposed by the community helped you, consider accepting it, accept an answer is the best way to thank those who helped you, it will also help those who have the same problem and still keep the site healthy because your question ceases to be an unresolved question. -- It’s only worth you take a look at our [Tour] =D

  • Giovanni, don’t forget that you can also vote in all the answers you found useful. Votes are an important tool on the site, besides being a way to recognize the efforts of those who asked and answered (obviously it is not an obligation, but if you think the answers were useful, consider voting for them) :-)

2 answers

1

You need to go through each of the positions of lista to then access the k and v of each of them.

In practice, his last for end would look like this:

for aluno in lista:
    for k,v in aluno.items():
        print(k,':', v)

Here I access each aluno in lista, that is to say, lista[0] and then lista[1], and do the print() of the key k and the value v of each of the items().

  • Thank you very much, I was really missing from the top, because I was going through the list, not the student on each list, with the first being I go through the student A and the student B and then with the second is I display the key and the value

0


As explained by reply from @Rafael, you need to go through the entire list to print the data of all students. By doing lista[1], you are only accessing the second student (since arrays begin with the zero index: the first element is lista[0], the second is lista[1], etc.).

But there are still other details you can change if you want.

Instead of creating the dictionary aluno outside the loop and make a copy every time, you can create it inside the loop:

for i in range(2):
    aluno = dict() # cria um novo dicionário
    ... # lê os dados do aluno
    lista.append(aluno) # não precisa copiar

Or you can move all the creation logic of a student to a function:

# lê os dados do aluno e retorna o dicionário com esses dados
def ler_dados_aluno(i):
    aluno = dict()
    aluno['Nota'] = int(input(f'Digite o nota do aluno {i + 1}: '))
    aluno['Matricula'] = int(input(f'Digite o numero da matricula: '))
    aluno['Frequencia'] = int(input('Digite a frequencia em porcentagem: '))
    return aluno

And then you can create the list using the syntax of comprehensilist on:

lista = [ler_dados_aluno(i) for i in range(2)]

The above code is equivalent to:

lista = []
for i in range(2):
    lista.append(ler_dados_aluno(i))

But the comprehensilist on, in addition to more succinct, is considered the most pythonic.

Already to print the list, enjoy that you already have available the f-strings and use them:

for i, aluno in enumerate(lista):
    print(f'Dados do aluno {i + 1}:')
    for k, v in aluno.items():
        print(f'- {k} : {v}') # use a f-string para imprimir a chave e valor de uma vez

Note that I gave an "increment". I used enumerate to have, in addition to the student, the respective index of him in the list (only to be able to print "Student X data"), and also used the f-strings to print the information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.