def get_best_dataset_key(key, choices):
    if key.wavelength is not None and choices:
        nearest_wl = min([_wl_dist(key.wavelength, x.wavelength)
                          for x in choices if x.wavelength is not None])
        choices = [c for c in choices
                   if _wl_dist(key.wavelength, c.wavelength) == nearest_wl]
    if key.modifiers is None and choices:
        num_modifiers = min(len(x.modifiers or tuple()) for x in choices)
        choices = [c for c in choices if len(
            c.modifiers or tuple()) == num_modifiers]
    if key.calibration is None and choices:
        best_cal = [x.calibration for x in choices if x.calibration]
        if best_cal:
            best_cal = min(best_cal, key=lambda x: CALIBRATION_ORDER[x])
            choices = [c for c in choices if c.calibration == best_cal]
    if key.resolution is None and choices:
        low_res = [x.resolution for x in choices if x.resolution]
        if low_res:
            low_res = min(low_res)
            choices = [c for c in choices if c.resolution == low_res]
    if key.level is None and choices:
        low_level = [x.level for x in choices if x.level]
        if low_level:
            low_level = max(low_level)
            choices = [c for c in choices if c.level == low_level]
    return choices