import json


def get_value_text(values, value, text_key):
    """
    Get the text for the given value, using the given text_key.

    Values is a meta object in the form of a list of dicts. This
    function is used to find in that list the dict that has the given
    value, and from it return the text for that value using the given
    text_key.

    Parameters
    ----------
    values : list
        A Quantipy values meta object.
    value : int
        The value that should targeted in the list of values.
    text_key : str
        The key from which the the value text should be taken.

    Returns
    -------
    text : str
        The text associated with the targeted value and text_key.
    """

    for val in values:
        if val['value']==value:
            try:
                text = val['text'][text_key]
                return text
            except KeyError:
                print (
                    "The text key '%s' was not found in the text object: %s" % (
                        text_key,
                        json.dumps(val)
                    )
                )
    raise ValueError(
            "The value '%s' was not found in the values object: %s" % (
                value,
                json.dumps(values)
            )
        )