How to Convert a Dictionary to an Attribute in Python?

Estimated read time 2 min read

To convert a dictionary to an attribute in Python, you can use the setattr() function to dynamically set attributes on an object. Here’s an example:

class MyObject:

def dict_to_attributes(dictionary, obj):
    for key, value in dictionary.items():
        setattr(obj, key, value)

# Example usage
my_dict = {"name": "John", "age": 30, "city": "New York"}

my_object = MyObject()
dict_to_attributes(my_dict, my_object)

print(  # Output: John
print(my_object.age)   # Output: 30
print(  # Output: New York

In this example, we define a class MyObject to create an empty object.

We define a function dict_to_attributes that takes a dictionary and an object as inputs. The function iterates over the key-value pairs in the dictionary using the items() method. For each key-value pair, it sets an attribute on the object using the setattr() function.

Finally, we create a dictionary my_dict with key-value pairs representing attributes. We create an instance of MyObject called my_object and pass both the dictionary and the object to the dict_to_attributes function. This function dynamically sets the attributes on the my_object based on the dictionary values.

We then print the attributes of the my_object, which were set dynamically from the dictionary.

Note that the setattr() function can be used to set attributes on any object, whether it’s an instance of a class or a built-in object. However, if you want to access the attributes in a dictionary-like manner (using square brackets), you can consider using a dictionary directly instead of converting it to attributes.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply