Convert `ledger balance` output into an hierarchical data structure.

def balance(output):
    """Convert `ledger balance` output into an hierarchical data structure."""
    lines = map(pattern.search, output.splitlines())

    stack = []
    top = []
    for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
        # pop items off stack while current item has indent <=
        while stack and item['indent'] <= stack[-1]['indent']:
            stack.pop()

        # check if this is a top-level item
        if not stack:
            stack.append(item)
            top.append(item)
        else:
            item['parent'] = stack[-1]
            stack[-1]['children'].append(item)
            stack.append(item)

    return top