Python Create Dictionary From Object

1. Introduction

Creating a dictionary from an object's properties is a common task in Python, which can be especially useful in areas like object serialization, where object attributes need to be converted into a format that can be easily stored or transmitted. Python's built-in vars() function can be used to perform this operation.

Definition

A dictionary in Python is a collection of key-value pairs. Creating a dictionary from an object involves extracting the object’s attributes (keys) and their corresponding values.

2. Program Steps

1. Define a class with some attributes.

2. Create an instance of the class.

3. Use the vars() function to convert the object's attributes to a dictionary.

4. Print the resulting dictionary.

3. Code Program

# Define a class with some attributes
class MyClass:
    def __init__(self, name, age, country):
        self.name = name
        self.age = age
        self.country = country

# Create an instance of the class
obj = MyClass(name="John", age=30, country="USA")

# Convert the object's attributes to a dictionary
obj_dict = vars(obj)

# Print the dictionary
print("The dictionary created from the object is:")
for key, value in obj_dict.items():
    print(f"{key}: {value}")

Output:

The dictionary created from the object is:
name: John
age: 30
country: USA

Explanation:

1. MyClass is a class with an __init__ method that initializes name, age, and country attributes.

2. obj is an instance of MyClass with attribute values "John", 30, and "USA".

3. vars(obj) is used to convert obj's attributes to a dictionary, where keys are the names of the attributes and values are the attribute values.

4. obj_dict stores the dictionary representation of obj.

5. A for loop iterates over obj_dict.items(), which contains the dictionary items, and prints each key-value pair.

6. The output demonstrates that the attributes of the object have been successfully converted into a dictionary format.

Comments