In python, how do I cast a class object to a dict

| | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Let"s say I"ve got a simple class in python

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version="old"):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __what_goes_here__(self):
        return {"a": self.a, "b": self.b, "c": self.c}

I can cast it to an integer very easily

>>> w = Wharrgarbl("one", "two", "three", 6)
>>> int(w)
9006

Which is great! But, now I want to cast it to a dict in a similar fashion

>>> w = Wharrgarbl("one", "two", "three", 6)
>>> dict(w)
{"a": "one", "c": "three", "b": "two"}

What do I need to define for this to work? I tried substituting both __dict__ and dict for __what_goes_here__, but dict(w) resulted in a TypeError: Wharrgarbl object is not iterable in both cases. I don"t think simply making the class iterable will solve the problem. I also attempted many googles with as many different wordings of "python cast object to dict" as I could think of but couldn"t find anything relevant :{

Also! Notice how calling w.__dict__ won"t do what I want because it"s going to contain w.version and w.sum. I want to customize the cast to dict in the same way that I can customize the cast to int by using def int(self).

I know that I could just do something like this

>>> w.__what_goes_here__()
{"a": "one", "c": "three", "b": "two"}

But I am assuming there is a pythonic way to make dict(w) work since it is the same type of thing as int(w) or str(w). If there isn"t a more pythonic way, that"s fine too, just figured I"d ask. Oh! I guess since it matters, this is for python 2.7, but super bonus points for a 2.4 old and busted solution as well.

There is another question Overloading __dict__() on python class that is similar to this one but may be different enough to warrant this not being a duplicate. I believe that OP is asking how to cast all the data in his class objects as dictionaries. I"m looking for a more customized approach in that I don"t want everything in __dict__ included in the dictionary returned by dict(). Something like public vs private variables may suffice to explain what I"m looking for. The objects will be storing some values used in calculations and such that I don"t need/want to show up in the resulting dictionaries.

UPDATE: I"ve chosen to go with the asdict route suggested but it was a tough choice selecting what I wanted to be the answer to the question. Both @RickTeachey and @jpmc26 provided the answer I"m going to roll with but the former had more info and options and landed on the same result as well and was upvoted more so I went with it. Upvotes all around though and thanks for the help. I"ve lurked long and hard on stackoverflow and I"m trying to get my toes in the water more.

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from In python, how do I cast a class object to a dict, check other ast Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Javier Jackson

Rome | 2023-01-29

io Python module is always a bit confusing 😭 In python, how do I cast a class object to a dict is not the only problem I encountered. Checked yesterday, it works!

Angelo Ungerschaft

Paris | 2023-01-29

Simply put and clear. Thank you for sharing. In python, how do I cast a class object to a dict and other issues with os Python module was always my weak point 😁. Will use it in my bachelor thesis

Manuel Williams

Tallinn | 2023-01-29

Thanks for explaining! I was stuck with In python, how do I cast a class object to a dict for some hours, finally got it done 🤗. Will use it in my bachelor thesis

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically