make a dictionary of attributes of a class

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Help me please

I have this class and I want to make a dictionary of it

class Building:
 
    # building type
    var type : int
 
    # building texture
    var iconTexture : Texture
 
    # resource the building produces
    var prodResource : int = 0
    var prodResourceAmount : int

    func _init (type, iconTexture, prodResource, prodResourceAmount):
        self.type = type
        self.iconTexture = iconTexture
        self.prodResource = prodResource
        self.prodResourceAmount = prodResourceAmount
    func _ready():
        var base = Building.new(0, preload("res://Base.png"), 0, 0)
        var mine = Building.new(1, preload("res://Mine.png"), 2, 1)
        var greenhouse = Building.new(2, preload("res://Greenhouse.png"), 1, 1)
        var solarpanel = Building.new(3, preload("res://SolarPanel.png"), 4, 1)

I had copied it from a tutorial and now I want to convert these four building’s attribute into a dictionary. please tell how can i do it

:bust_in_silhouette: Reply From: TimiT

Is it?

Dictionary syntax:

var _dict = {
    "keyName": value
}

For your example:

var _dict = {
    "type": null,
    "iconTexture": null,
    "prodResource ": 0,
    "prodResourceAmount": 0
}

...

_dict.type = object.type
# or
_dict.type = 10

UPD

Okay, I found other solution. You can dynamicully get class’es properties and set them in dictionary

var b = Building.new(...)
var _dict = {}
for i in b.get_property_list():
	if i.name != "Reference" and i.name != "script" and i.name != "Script Variables":
		_dict[i.name] = b[i.name]
print(_dict)

Read more:

Thanks! It is helpful but can you tell the reason of the if statement below for

Help me please | 2021-06-22 14:15

This values returns with your properties (are they Godot’s system?) and we should remove them from our dict.

TimiT | 2021-06-22 14:19

Don’t know. I just want to know the reason why we used that. I don’t know what are they and why we used them

Help me please | 2021-06-22 14:24

I answered here:

This values returns with your properties

Is it all what you want to know?

TimiT | 2021-06-22 14:28

Got it!
Thanks :slight_smile:

Help me please | 2021-06-22 14:37