Passing a list of objects to a dictionary in python

1

I have a list of objects:

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

Each object stores information, including the information itself, eg: 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 in a dictionary structure, this way below, 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 the dic and to .. is this wrong way to add elements in dic?

    
asked by anonymous 08.11.2017 / 13:05

1 answer

1

Yes, it is wrong. Note that you are setting cont = 1 within your loop repetition, so at the beginning of each iteration, the value of cont returns to 1, always adding the object to the same key in the dictionary.

You could just remove this initialization from the for loop:

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 at Ideone | Repl.it

So the output would be:

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

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

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

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

print(dic)

See working at Ideone | Repl.it

Producing output:

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

Or, without using the loopback, you can use the zip function in conjunction with the range function:

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

See working at Ideone | Repl.it

Producing output:

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