Dictionary with FOR loop in Python

Asked

Viewed 680 times

0

While I study Python, time or other unpacking my own exercises. Only this time I 'Stopped' when I decided to do the code below.

for c in range (3):
    bd = {}
    nome = input('Insira seu nome: ')
    sobrenome = input('Insira seu sobrenome: ')
    bd [nome] = sobrenome
print ()
print (bd)

The question is, how do I feed the dictionary using the for (for example) if at the end of loop she only shows me the last key-value pair that I typed in?

1 answer

1

This isn’t a library, it’s a dictionary. Do not confuse these terminologies, libraries is also a term used in programming, and refers to something completely different.

The problem with your for, is that you restart your dictionary every time you interact over the loop. Start the dictionary out of the loop, this should solve.

bd = {}
for c in range (3):
    nome = input('Insira seu nome: ')
    sobrenome = input('Insira seu sobrenome: ')
    bd [nome] = sobrenome
  • Hello "user145470", I am studying other technologies in which the word DICTIONARY appears frequently, so when asking a question here in the community I ended up getting confused. I know the difference between library and dictionary but still thank you for the initiative. The code worked!

Browser other questions tagged

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