Prepares parameters to be sent to challonge.com.

    The `prefix` can be used to convert parameters with keys that
    look like ("name", "url", "tournament_type") into something like
    ("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
    which is how challonge.com expects parameters describing specific
    objects.

def _prepare_params(dirty_params, prefix=None):
    """Prepares parameters to be sent to challonge.com.

    The `prefix` can be used to convert parameters with keys that
    look like ("name", "url", "tournament_type") into something like
    ("tournament[name]", "tournament[url]", "tournament[tournament_type]"),
    which is how challonge.com expects parameters describing specific
    objects.

    """
    if prefix and prefix.endswith('[]'):
        keys = []
        values = []
        for k, v in dirty_params.items():
            if isinstance(v, (tuple, list)):
                keys.append(k)
                values.append(v)
        firstiter = ((k, v) for vals in zip(*values) for k, v in zip(keys, vals))
        lastiter = ((k, v) for k, v in dirty_params.items() if k not in keys)
        dpiter = itertools.chain(firstiter, lastiter)
    else:
        dpiter = dirty_params.items()

    params = []
    for k, v in dpiter:
        if isinstance(v, (tuple, list)):
            for val in v:
                val = _prepare_value(val)
                if prefix:
                    params.append(("%s[%s][]" % (prefix, k), val))
                else:
                    params.append((k + "[]", val))
        else:
            v = _prepare_value(v)
            if prefix:
                params.append(("%s[%s]" % (prefix, k), v))
            else:
                params.append((k, v))

    return params