In classes how can I put a dictionary in a list?


Good, my doubt is probably very basic but I am not able to solve it. It basically consists of how I can add my turtle dictionary to the turtle list. I've tried with append but it tells me that turtles are not defined, any suggestions? The example is as follows:

class Galapago:

    def __init__(self):

        self.x= 0
        self.sprite= "lo"
        self.color= "bue"
        tortuga['sprite']= self.sprite
        tortuga['color']= self.color

I am looking to create this list (turtles) so that I can then use its data in other functions, such as the following:

    def set_pencolor(self,color):
        for n in range (len(tortugas)):
            if tortugas[n]['sprite']== sprite:
                for m in tortugas[n]:
                    tortugas[n]['color']= color
asked by airun 28.12.2018 в 14:50

2 answers


Python dictionaries, like almost all iterable types, can easily be converted into iterables of another type. In this case it would be worth with nuevalista = list(tortugas)

For example if we have this dictionary:

tortugas = {"sprite": "tortuga1", "x": 7, "color": "verde", "Enferma": False}

You can list the dictionary keys like this:

>>> tortugas_k = list(tortugas)
>>> tortugas_k
['sprite', 'x', 'color', 'Enferma']

If what you want is to pass the dictionary values to a list:

>>> tortugas_v = list(tortugas.values())
>>> tortugas_v
['tortuga1', 7, 'verde', False]

And finally, if you want to keep both the keys and the values, they can be encapsulated in a tuple and then added to a list:

>>> tortugas2 = [(k, v) for k, v in tortugas.items()]
>>> tortugas2
[('sprite', 'tortuga1'), ('x', 7), ('color', 'verde'), ('Enferma', False)]

The fact that you are inside a class is irrelevant

answered by 28.12.2018 в 15:33

you can do it like this:

class Galapago:
    #variables de clase
    x= 0
    sprite= "lo"
    color= "bue"

    def __init__(self):

        tortuga['sprite']= self.sprite
        tortuga['color']= self.color

    # para obtener la lista
    def get_tortugas(self):
        return self.tortugas

g = Galapago();
answered by 28.12.2018 в 15:26