Dictionary for objects in Python

Asked

Viewed 343 times

-1

I wonder how I can assign a dictionary to a set of objects.

For example, I have a 4x4 vector of 'neuron' objects': [[<__main__.Neuronio object at 0x1035644e0>, <__main__.Neuronio object at 0x103564518>, <__main__.Neuronio object at 0x103564550>, <__main__.Neuronio object at 0x103564588>], [<__main__.Neuronio object at 0x1035645c0>, <__main__.Neuronio object at 0x1035645f8>, <__main__.Neuronio object at 0x103564630>, <__main__.Neuronio object at 0x103564668>], [<__main__.Neuronio object at 0x1035646a0>, <__main__.Neuronio object at 0x1035646d8>, <__main__.Neuronio object at 0x103564710>, <__main__.Neuronio object at 0x103564748>], [<__main__.Neuronio object at 0x103564780>, <__main__.Neuronio object at 0x1035647b8>, <__main__.Neuronio object at 0x1035647f0>, <__main__.Neuronio object at 0x103564828>]]

And I would like to work with the respective dictionary as if when working with the dictionary ('1') would have referenced the map[0][0], object <main.Neuronio Object at 0x1035644e0> and so consecutively for dictionary (2...3...n) referencing matrix objects.

1 answer

2

I start by saying that for elemento in len(range(iteravel)) is always the wrong way to iterate in python. The correct is to use for elemento in iteravel, or in cases that need the Dice can use the function enumerate:

for indice, elemento in enumerate(iteravel):

But in your case you don’t need the Dice, as you are only assigning based on the contador. So just do it like this:

dicionario_mapa = {}
contador = 1

for linha in mapa:
    for valor in linha:
        dicionario_mapa[contador] = valor
        contador += 1

print(dicionario_mapa)

See this example working on Ideone

Another interesting solution would be using chain of itertools, that allows you to join several variables into one, as if you already have a single list instead of lists. Then with the enumerate function you can get the position you want without having to use the variable contador:

from itertools import chain
dicionario_mapa = {}
for posicao, valor in enumerate(chain(*mapa)):
    dicionario_mapa[posicao + 1] = valor

print(dicionario_mapa)

See also this version on Ideone

A see that only now has an assignment on for, can also turn this into comprehensilist on, where only one row is the part where the values are assigned:

from itertools import chain
dicionario_mapa = { posicao+1: valor for posicao, valor in enumerate(chain(*mapa)) }

print(dicionario_mapa)

See this latest version on Ideone

Browser other questions tagged

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