create an class with a dictionnary as attribue in python

Here's an example of a class with a dictionary attribute in Python:

main.py
class MyClass:
    def __init__(self):
        self.my_dict = {}
65 chars
4 lines

In this class, my_dict is an attribute that is set to an empty dictionary in the constructor (__init__) using self.my_dict = {}. You can then access and modify this dictionary attribute using the instance of MyClass.

For example, you can add a key-value pair to the dictionary like this:

main.py
my_instance = MyClass()
my_instance.my_dict["my_key"] = "my_value"
67 chars
3 lines

And you can access the value associated with "my_key" like this:

main.py
print(my_instance.my_dict["my_key"])  # Output: "my_value"
59 chars
2 lines

gistlibby LogSnag