import re


def extract_key_value_pairs(tokenized_lines,conversions):
    """ Parse tokenized lines as key-value pairs.

    A valid key-value line is of the form:

       [<key>,"=",<v1>,...]

    An "null" key-value line will be silently ignored:

       [<key>,"="]


    Values are only retained if a conversion is specified
    for that key string.

    >>> test_lines = ["a = 1","b = 1 2 3","c = 42"]
    >>> tokenized_lines = split_and_prune_lines(test_lines)
    >>> conversions = {"a" : singleton_of(int), "b" : list_of(int)}
    >>> extract_key_value_pairs(tokenized_lines,conversions)
    {'b': [1, 2, 3], 'a': 1}

    Arguments:
        tokenized_lines (iterator): tokenized input lines
        conversions (dict): conversion functions for recognized key strings

    Returns:
        (dict): key value pairs obtained through given conversions
    """

    # regexp for Fortran array-like output
    array_regexp = re.compile(r'([a-zA-Z0-9]+)\([0-9\*]\)')

    results = dict()
    for tokenized_line in tokenized_lines:

        # skip "null" key-value line
        null_line = (len(tokenized_line)==2) and (tokenized_line[1]=="=")
        if (null_line):
            continue

        # validate line format
        valid_line = (len(tokenized_line)>=3) and (tokenized_line[1]=="=")
        if (not valid_line):
            raise ValueError("expected key-value line but found {}".format(tokenized_line))

        # extract line parts
        key = tokenized_line[0]
        value_strings = tokenized_line[2:]

        # convert and store value
        if (key in conversions):
            results[key] = conversions[key](value_strings)
        else:
            # try to handle array types
            match = array_regexp.match(key)
            if match and (match.group(1) in conversions):
                key = match.group(1)
                if key in results:
                    results[key] += [conversions[key](value_strings)]
                else:
                    results[key] = [conversions[key](value_strings)]

    return results