Suppose you have the following:
dados = {"batata": [1, 2, 3], "abacaxi": [4, 5, 6]}
And then you do it:
names = ['macaco', 'gato']
dados.keys() = names
Which of these would be the result?
dados = {"macaco": [1, 2, 3], "gato": [4, 5, 6]}
dados = {"gato": [1, 2, 3], "macaco": [4, 5, 6]}
The answer is none. That way, there’s no way python knows which key would be replaced by the monkey and which one would be replaced by the cat. So, what you’re gonna have to do is this:
dados = {"indice1": [1, 2, 3], "indice2": [4, 5, 6]}
troca = {"indice1": "nome1", "indice2": "nome2"}
dados2 = {}
for k in dados:
dados2[troca[k]] = dados[k]
The dictionary troca
serves to tell which key of the dados
shall be replaced by another key in the dados2
.
The for
goes through every key k
of dados
and uses it to access the corresponding value (dados[k]
) and the name of the new key (troca[k]
) for this to populate the dictionary dados2
.
Keys cannot be renamed. They are immutable.
– Rodrigo Nogueira
From Python 3.7, to insertion order in a dictionary is guaranteed. So in Python >= 3.7 your answer would work with a common dictionary as well.
– jfaccioni
Thank you very much Lacobus! Your knowledge has helped me a lot!!!
– Patricia Padula Lopes