In the near future, I will often need to convert some data to netcdf format. I have a long list of global attributes that need assigning to the dataset. For example, to assign the global attribute title
to a dataset ds
, I can do
ds.title = 'my_title'
However, I would like my code to be reusable, and my list of global attributes will differ between datasets. Therefore, I would like to be able to provide the name of the global attribute (title
in the example above) using a variable, something like
var = title
ds.var = 'my_title'
However, the above example would create a global attribute named 'var', which is not what I want. Is is possible to do something like this?
More specifically, I will be creating a dictionary where the keys will be the global attribute names and the items will be the content to be stored.
Many thanks in advance for you help.
What you want is setattr
to set attributes based on a string:
my_attrs = dict(title='my_title', author='me')
for name, value in my_attrs.items():
setattr(ds, name, value)