When creating a new pair in a dictionary lose the previous data?

Asked

Viewed 32 times

0

I’m creating a Dict from scratch, but when I add some new pair, the old pair gets lost. If I try to print 'name' for example, it gives error.

cidade = {
    'nome': 'São Paulo',
    'estado': 'São Paulo'
}

print(cidade)    
print(cidade['nome'])    
cidade = {'país': 'Brasil'}    
#print(cidade['nome'])    
print(cidade)

Take the penultimate comment print() that you will see the mistake happening.

1 answer

5


You are not creating a new key and value pair, you are creating a new dictionary and saving in it variable, so its previous value is lost, since it cannot store two different values in the same variable.

If you want to add a new element you should create it through the standard dictionary syntax saying that you have a key that did not exist before and storing a value in the key and not in the dictionary. The key is like a different variable, that is, the dictionary is an object full of variables.

Another way is to use a method that the dictionary object has by default and it changes the object for you. Documentation.

cidade = {
    'nome': 'São Paulo',
    'estado': 'São Paulo'
}
cidade['país'] = 'Brasil'
cidade.update({'cep': '01000'})
print(cidade)

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

Browser other questions tagged

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