How to fix cfgrib TypeError: open_dataset() got an unexpected keyword argument 'filter_by_keys'

Problem:

You want to open a GRB2 file using the cfgrib library using code like

import xarray as xr
ds = xr.open_dataset('myfile.grb2', engine='cfgrib', filter_by_keys={'typeOfLevel': 'atmosphere'})

But you see an exception like

TypeError: open_dataset() got an unexpected keyword argument 'filter_by_keys'

Solution

You can’t use filter_by_keys=… as argument to xr.open_dataset() directly. You need to use backend_kwargs like this:

ds = xr.open_dataset('myfile.grb2', engine='cfgrib', backend_kwargs={'filter_by_keys': {'typeOfLevel': 'atmosphere'}})