w3resource

Python: Get a dictionary from an object's fields


16. Get Dictionary from an Object's Fields

Write a Python program to get a dictionary from an object's fields.

Sample Solution:-

Python Code:

# Define a class 'dictObj' that inherits from the 'object' class.
class dictObj(object):
    # Define the constructor method '__init__' for initializing object attributes.
    def __init__(self):
        # Initialize attributes 'x', 'y', and 'z' with string values.
        self.x = 'red'
        self.y = 'Yellow'
        self.z = 'Green'
    
    # Define a method 'do_nothing' that doesn't perform any actions (placeholder).
    def do_nothing(self):
        pass

# Create an instance 'test' of the 'dictObj' class.
test = dictObj()

# Print the '__dict__' attribute of the 'test' object, which contains its attribute-value pairs.
print(test.__dict__) 

Sample Output:

{'x': 'red', 'y': 'Yellow', 'z': 'Green'}

For more Practice: Solve these Related Problems:

  • Write a Python program to create a dictionary from the attributes of an object using the __dict__ attribute.
  • Write a Python program to iterate over an object's fields and convert them into a dictionary.
  • Write a Python program to implement a function that extracts public fields from a class instance and returns them as a dictionary.
  • Write a Python program to serialize an object's attributes into a dictionary using introspection.

Python Code Editor:

Previous: Write a Python program to get the maximum and minimum value in a dictionary.
Next: Write a Python program to remove duplicates from Dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.