How to create dict from class without None fields?

2024/7/3 23:24:12

I have the following dataclass:

@dataclass
class Image:content_type: strdata: bytes = b''id: str = ""upload_date: datetime = Nonesize: int = 0def to_dict(self) -> Dict[str, Any]:result = {}if self.id:result['id'] = self.idif self.content_type:result['content_type'] = self.content_typeif self.size:result['size'] = self.sizeif self.upload_date:result['upload_date'] = self.upload_date.isoformat()return result

Is there any way to simplify to_dict method? I don't want to list all of the fields using if.

Answer

As suggested by meowgoesthedog, you can use asdict and filter the result to skip falsy values:

from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Dict, Any@dataclass
class Image:content_type: strdata: bytes = b''id: str = ""upload_date: datetime = Nonesize: int = 0def to_dict(self) -> Dict[str, Any]:return {k: v for k, v in asdict(self).items() if v}print(Image('a', b'b', 'c', None, 0).to_dict())
# {'content_type': 'a', 'data': b'b', 'id': 'c'}
https://en.xdnf.cn/q/73237.html

Related Q&A

Is sys.exit equivalent to raise SystemExit?

According to the documentation on sys.exit and SystemExit, it seems thatdef sys.exit(return_value=None): # or return_value=0raise SystemExit(return_value)is that correct or does sys.exit do something …

Vertical overflow of table in live display should scroll the content

Im using a Live display to show the content of a Table which grows over time. Eventually there is a vertical overflow and in that case Id like the oldest (i.e. topmost) rows to vanish while the most re…

Reading KML Files Using Fastkml

Ive searched around quite a bit for this specific Python module, and havent been able to find a source which points me in the right direction.Im trying to read a KML file and display all of the feature…

Adding extra fields to django-registration form

I have a model called "Organization" that Ive setup as a User profile and I would like to have the fields from the "Organization" model show up on the registration page. How do I go…

Need to do a daily log rotation (0utc) using Python

Im an admitted noob to Python. Ive written a little logger that takes data from the serial port and writes it to a log file. Ive got a small procedure that opens the file for append, writes, then close…

Save/Load a Dictionary

Ive found a couple of others asking for help with this, but not specifically what Im trying to do. I have a dictionary full of various formats (int, str, bool, etc) and Im trying to save it so I can lo…

py2exe error handling redirection and popup

Been trying to figure out how to get py2exe to handle errors more gracefully. There are basically 2 weird things happening:1) Popup message after shutting down the program => want to suppress (not …

SQL statement for CSV files on IPython notebook

I have a tabledata.csv file and I have been using pandas.read_csv to read or choose specific columns with specific conditions.For instance I use the following code to select all "name" where …

How to draw ellipsoid with plotly

Are there any way to plot a surface like ellipsoid with plotly 3D?Currently only surfaces of the form z=f(x,y) are discussed in the docs. There is also Mesh 3D, but I found no examples for it. It seem…

PyTorch DataLoader uses same random seed for batches run in parallel

There is a bug in PyTorch/Numpy where when loading batches in parallel with a DataLoader (i.e. setting num_workers > 1), the same NumPy random seed is used for each worker, resulting in any random f…