Passing a list of objects to a python dictionary

Asked

Viewed 1,914 times

1

I have a list of objects:

lista_objetos = ['acarreta', 'afeta', 'alavancagem', 'apropriadas', 'arvore', 'avaliacao']

each object stores information, among that information the word itself, Ex: afeta.palavra is equal "afeta".

My goal is to enumerate these objects as follows:

1 - acarreta
2 - afeta
3 - alavancagem
4 - apropriadas
5 - arvore
6 - avaliacao

I’m trying to put this information into a dictionary, this way to follow, but it’s not working, what I’m doing wrong....

dic = {}

for objeto in lista_objeto:
    cont = 1
    dic[cont] = objeto.palavra
    cont += 1

it adds an item to dic and to.. it is wrong that way to add elements in dic?

1 answer

1


Yes, it’s wrong. Notice that you’re setting cont = 1 within its loop of repetition, then at the beginning of each iteration, the value of cont returns to 1, always adding the object in the same dictionary key.

You could just take that boot out of the loop for:

lista_objetos = ['acarreta', 'afeta', 'alavancagem', 'apropriadas', 'arvore', 'avaliacao']
dic = {}

cont = 1
for objeto in lista_objetos:
    dic[cont] = objeto #objeto.palavra
    cont += 1

print(dic)

See working on Ideone | Repl.it

So the exit would be:

{1: 'acarreta', 2: 'afeta', 3: 'alavancagem', 4: 'apropriadas', 5: 'arvore', 6: 'avaliacao'}

Or, in the most pythonica, you can use the function enumerate:

lista_objetos = ['acarreta', 'afeta', 'alavancagem', 'apropriadas', 'arvore', 'avaliacao']
dic = {}

for chave, objeto in enumerate(lista_objetos):
    dic[chave] = objeto

print(dic)

See working on Ideone | Repl.it

Producing the output:

{0: 'acarreta', 1: 'afeta', 2: 'alavancagem', 3: 'apropriadas', 4: 'arvore', 5: 'avaliacao'}

Or, without using the loop, you can use the function zip together with the function range:

dic = dict( zip(range(len(lista_objetos)), lista_objetos) )

See working on Ideone | Repl.it

Producing the output:

{0: 'acarreta', 1: 'afeta', 2: 'alavancagem', 3: 'apropriadas', 4: 'arvore', 5: 'avaliacao'}
  • Gee... I didn’t even realize it, this cont = 1 inside the loop that was holding me back.. Thanks @andersoncarloswoss

Browser other questions tagged

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