def to_dict(qresults, key_function=lambda rec: rec.id):
    """Turns a QueryResult iterator or list into a dictionary.

     - qresults     - Iterable returning QueryResult objects.
     - key_function - Optional callback function which when given a
                      QueryResult object should return a unique key for the
                      dictionary.

    This function enables access of QueryResult objects from a single search
    output file using its identifier.

    >>> from Bio import SearchIO
    >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml')
    >>> search_dict = SearchIO.to_dict(qresults)
    >>> sorted(search_dict)
    ['gi|156630997:105-1160', ..., 'gi|371502086:108-1205', 'gi|53729353:216-1313']
    >>> search_dict['gi|156630997:105-1160']
    QueryResult(id='gi|156630997:105-1160', 5 hits)

    By default, the dictionary key is the QueryResult's string ID. This may be
    changed by supplying a callback function that returns the desired identifier.
    Here is an example using a function that removes the 'gi|' part in the
    beginning of the QueryResult ID.

    >>> from Bio import SearchIO
    >>> qresults = SearchIO.parse('Blast/wnts.xml', 'blast-xml')
    >>> key_func = lambda qresult: qresult.id.split('|')[1]
    >>> search_dict = SearchIO.to_dict(qresults, key_func)
    >>> sorted(search_dict)
    ['156630997:105-1160', ..., '371502086:108-1205', '53729353:216-1313']
    >>> search_dict['156630997:105-1160']
    QueryResult(id='gi|156630997:105-1160', 5 hits)

    Note that the callback function does not change the QueryResult's ID value.
    It only changes the key value used to retrieve the associated QueryResult.

    As this function loads all QueryResult objects into memory, it may be
    unsuitable for dealing with files containing many queries. In that case, it
    is recommended that you use either `index` or `index_db`.

    """
    qdict = {}
    for qresult in qresults:
        key = key_function(qresult)
        if key in qdict:
            raise ValueError("Duplicate key %r" % key)
        qdict[key] = qresult
    return qdict