Specify encoding/compression for many variables in xarray dataset when write to_netcdf
I'd just create the encoding parameter dynamically:
comp = dict(zlib=True, complevel=5)
encoding = {var: comp for var in ds.data_vars}
ds.to_netcdf(filename, encoding=encoding)