Format and sort a list of pairs, usually for printing.

    If sort_key is provided, the value will be passed as the
    'key' keyword argument of the sorted() function when
    sorting the items. This allows for the input such as
    [('A', 3), ('B', 5), ('Z', 1)] to be sorted by the ints
    but formatted like so:

        l = [('A', 3), ('B', 5), ('Z', 1)]
        print(fmt_pairs(l, sort_key=lambda x: x[1]))

            Z 1
            A 3
            B 5
        where the default behavior would be:

        print(fmt_pairs(l))

            A 3
            B 5
            Z 1

def fmt_pairs(obj, indent=4, sort_key=None):
    """Format and sort a list of pairs, usually for printing.

    If sort_key is provided, the value will be passed as the
    'key' keyword argument of the sorted() function when
    sorting the items. This allows for the input such as
    [('A', 3), ('B', 5), ('Z', 1)] to be sorted by the ints
    but formatted like so:

        l = [('A', 3), ('B', 5), ('Z', 1)]
        print(fmt_pairs(l, sort_key=lambda x: x[1]))

            Z 1
            A 3
            B 5
        where the default behavior would be:

        print(fmt_pairs(l))

            A 3
            B 5
            Z 1
    """
    lengths = [len(x[0]) for x in obj]
    if not lengths:
        return ''
    longest = max(lengths)
    obj = sorted(obj, key=sort_key)
    formatter = '%s{: <%d} {}' % (' ' * indent, longest)
    string = '\n'.join([formatter.format(k, v) for k, v in obj])
    return string