def METHOD_NAME(key, header):
    if isinstance(key, KeySet):
        kid = header.get('kid')
        if kid:
            return key.find_by_kid(kid)
        rv = random.choice(key.keys)
        # use side effect to add kid value into header
        header['kid'] = rv.kid
        return rv
    if isinstance(key, dict) and 'keys' in key:
        keys = key['keys']
        kid = header.get('kid')
        for k in keys:
            if k.get('kid') == kid:
                return k
        if not kid:
            rv = random.choice(keys)
            header['kid'] = rv['kid']
            return rv
        raise ValueError('Invalid JSON Web Key Set')
    # append kid into header
    if isinstance(key, dict) and 'kid' in key:
        header['kid'] = key['kid']
    elif isinstance(key, Key) and key.kid:
        header['kid'] = key.kid
    return key