Doubt how to display the name of a dictionary key

Asked

Viewed 129 times

4

It is possible to display the name of only one key of a dictionary? ex:

notas_por_materias = { "Matematica" : 7,
                       "Portugues" : 8,
                       "Historia" : 10 }

I can display a print showing the subject name and then her note? Ex:

print (f"Sua nota em {Matematica}, foi de {nota_por_materias["Matematica"]}")

I can display the value of the note, but I cannot do the same with the name of the subject. I tried to pass as index [0] and as notas_por_materias.keys(0), but without success. I know there are many other ways to do this, but as I am learning to use dictionaries, I would like to know how to display through them.

1 answer

5


What you’re doing doesn’t make much sense. If you know what you want to print then you have no reason to do any different than what you did, except not use these keys. There are syntax errors in this too (variable name spelled wrong, confusion between double quotes and simple to separate what is the text and what is the key of the dictionary, done so he thinks the dictionary is closing the text), doing everything right would be like this:

print (f"Sua nota em Matemática, foi de {notas_por_materias['Matematica']}")

If you want to do in a loop, there would be more or less sense in generalizing the name of matter, but there is another problem. One of the reasons that it doesn’t make so much sense is because the key is a data written in a very simple way to facilitate the code and whatever is printed is something presentable for a human being, are different concepts, only in this example we already see a problem, the key has no accent and what you want to present has, outside it starts with uppercase which may not be what you want in the text in some scenarios. If you want to insist on it, it would be something like this:

for key, value in notas_por_materias.items() :
    print (f"Sua nota em {key}, foi de {value}")

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I was able to understand the mistake, thank you for your help!!

Browser other questions tagged

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