Python Program to Create Dictionary from an Object

This is a Python Program to form a dictionary from an object of a class.

Problem Description

The program forms a dictionary from an object of a class.

Problem Solution

1. Declare a class named A.
2. Initialize the keys with their values in the __init__ method of the class and form a dictionary using the __dict__ method.
3. Print the dictionary formed from the object of the class.
4. Exit.

Program/Source Code

Here is source code of the Python Program to form a dictionary from an object of a class. The program output is also shown below.

class A(object):  
     def __init__(self):  
         self.A=1  
         self.B=2  
obj=A()  
print(obj.__dict__)
Program Explanation

1. A class named A is declared.
2. The keys are initialized with their values in the __init__ method of the class.
3. The dictionary is formed using the object of the class and by using the __dict__ method.
4. The dictionary formed from the object of the class is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
{'A': 1, 'B': 2}

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.