How to name the keys of a dictionary from a list (array)?

Asked

Viewed 94 times

1

If I have a dictionary of this kind:

dados = {"indice1": [1, 2, 3], "indice2": [4, 5, 6]} 

and want to name its keys: indice1, indice2 with the following array:

names= ['nome1', 'nome2'] 

I can do this?

dados.keys()=names 

In such a way that it returns to me:

dados = {"nome1": [1, 2, 3], "nome2": [4, 5, 6]} 

Otherwise, what would be the right way?

2 answers

2

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.

1


There is no guarantee that your dictionary keys would be renamed correctly! Python dictionaries do not support sorting of your keys!

The closest you could come to this would be using the class OrderedDict module collections, look at you:

from collections import OrderedDict

dados = OrderedDict([("indice1",[1, 2, 3]),("indice2",[4, 5, 6])])
names = ['nome1', 'nome2']

novo = dict(zip(names, dados.values()))

print(novo)

Exit:

 {'nome1': [1, 2, 3], 'nome2': [4, 5, 6]}

Browser other questions tagged

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