HomePythonPython Program to Create Dictionary from an Object

Python Program to Create Dictionary from an Object

In Python, objects can have attributes that store various types of data. This program illustrates how to create a Python program that converts an object’s attributes into a dictionary.

Problem Statement

Write a Python program that takes an object as input and creates a dictionary containing its attributes as key-value pairs.

Python Program to Create Dictionary from an Object

class Person:
    def __init__(self, name, age, city):
        self.name = name
        self.age = age
        self.city = city

def object_to_dictionary(obj):
    obj_dict = {}
    for attribute in dir(obj):
        if not attribute.startswith("__") and not callable(getattr(obj, attribute)):
            obj_dict[attribute] = getattr(obj, attribute)
    return obj_dict

# Input (Creating an object)
name = input("Enter the person's name: ")
age = int(input("Enter the person's age: "))
city = input("Enter the person's city: ")
person_object = Person(name, age, city)

# Converting object to dictionary
person_dict = object_to_dictionary(person_object)

# Output
print("Dictionary representation of the object:", person_dict)
Python Program to Create Dictionary from an Object

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...