How can I make an instance-level dictionary in a PropertyGroup class?

I have a class that inherits PropertyGroup
I have lots of properties inside, and besides I want it to have also a dictionary that store different keys and values for each instance.
the problem is that all the instances share the same keys and values, so if I edit or append something of one instance, it’s affect all of them. and I can’t defined it as a instance-level because of the fact that PropertyGroup don’t allow using __init__.
is there anything I can do to make the dictionary instance-level variable?

example code for my class:

class code_example(bpy.types.PropertyGroup):
    string_prop: bpy.props.StringProperty()
    int_prop: bpy.props.IntProperty()

    dictionary = {}

Hi,
not sure if you can add dictionaries in that way. PropertyGroups manage properties. Adding different things is probably not the Blender-way.

What you can do instead is to use a CollectionProperty to simulate the dictionary behavior. Of course, the CollectionProperty is more like a list. But if you put the key that you would use in the dictionary into an extra property you can convert it into a real dict whenever needed. I know, not ideal, but that’s how I use it. If you find something better please let me know!

class dict_entry(bpy.types.PropertyGroup):
    key: bpy.props.StringProperty()
    value: bpy.props.FloatProperty()

class code_example(bpy.types.PropertyGroup):
    string_prop: bpy.props.StringProperty()
    int_prop: bpy.props.IntProperty()
    dict_like_collection: bpy.props.CollectionProperty(type=dict_entry)

# This does not work directly and is just a demo on how to use things
# You would need a proper reference to "code_example"
new_dict_entry = code_example.dict_like_collection.add()
new_dict_entry.key= "this_key"
new_dict_entry.value= 1.0

for this_entry in code_example.dict_like_collection:
    print(f"{this_entry.key} => {this_entry.value}")

1 Like

Actually, I Found a better solution, I think:
Any object in blender acts as a dictionary, so You can use it to store the key-value pairs, like this:

ef add_or_set_example(self, key:str, value:int):
        self["dict-"+key] = value

    def check_for_example(self, key:str) -> bool:
        if('dict-'+key in self.keys()):
            return True
        return False

    def get_example_value(self, key:str):
        return self["dict-"+key]

    def get_example_list(self):
        list= []
        for key in self.keys():
            if(key.startswith("dict-")):
                list.append(self[key])
        return list

    def remove_all_example(self,):
        for key in self.keys():
            if(key.startswith("dict-")):
                del self[key]

    def get_example_dict(self):
        dict = {}
        for key in self.keys():
            if(key.startswith("dict-")):
                node_trees[key[5:]]=self[key]
        return dict
    ```