Print value of a dictionary

Asked

Viewed 45 times

0

I have this issue to resolve, I need to display the note of the first name in the order of the flame, but I can only print the Key, the question is this:

Make a program in python that prompts the user to enter names and notes of 10 students. Next, the program should show the student note(a) that appears first in the call book.

my code so far:

dicionario = {}
for x in range(0, 3):
    nome = input("\nInsira o nome do aluno: ")
    nota = float(input("Insira a nota do aluno: "))
    dicionario[nome] = nota

newdict = sorted(dicionario)

print(newdict[0])

how do I print only the value of the first key of the dictionary?

1 answer

0

On line 7, where you create the variable newdict which receives the ordered dictionary, you are allocating it as a list, for example:

dicionario = {'Felipe': 4.0, 'Joao': 5.0, 'Ana': 7.8}
newdict = sorted(dicionario)
print(newdict)

Upshot:

['Ana', 'Felipe', 'Joao']

The correct thing would be for you to add the method .items() in front of the dictionary, see:

dicionario = {'Felipe': 4.0, 'Joao': 5.0, 'Ana': 7.8}
newdict = sorted(dicionario.items())
print(newdict)

Upshot:

[('Ana', 7.8), ('Felipe', 4.0), ('Joao', 5.0)]

Then showing the first item in your dictionary with newdict[0] he will return the note(a) student who appears first in the call book.

Finally, your code stays like this:

dicionario = {}
for x in range(0, 3):
    nome = input("\nInsira o nome do aluno: ")
    nota = float(input("Insira a nota do aluno: "))
    dicionario[nome] = nota

newdict = sorted(dicionario.items())

print(newdict[0][1])

See more about python dictionaries here!

  • Thank you very much, put on output it prints key and value, I just wanted the value

  • Just reference the value with [1]: print(newdict[0][1])

Browser other questions tagged

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