1

I am looking for a way to accessing and getting variables in an xarray dataset that can be included within a loop. I know that this code will list the variables name:

for ii in dataSet.data_vars:
    print(ii) 

I am looking for something similar that allows me to open each variable within the loop. I am new to python, migrating from Matlab, so detailed explanations would be greatly appreciated. Thank you.

1 Answers1

1

Xarray objects have a Dictionary interface which can be used for this kind of operations. In your particular case, you probably want:

for var_name, values in dataSet.items():
    # code

To iterate over dictionaries, you can use .items(), .keys() or .values(), depending on what you want to achieve. See Iterating over dictionaries using 'for' loops for one example, there are many.

OriolAbril
  • 7,315
  • 4
  • 29
  • 40
  • I ended up using `dataSet__getitem__(varname)` to access the variables through a loop. But many thanks for your reply, it will probably come handy for future issues – Lionel Arteaga May 27 '20 at 02:55
  • You can use `dataset[varname]`, you should not have to use `__getitem__` directly – OriolAbril May 27 '20 at 08:52
  • FWIW i had the same issue - this: `list(dataSet.data_vars)` also works well and returns a list of just the variable names. – Leah Wasser Dec 11 '20 at 17:52