def get_fieldnames(records):
    """
    Extract fieldnames for CSV headers from list of results

    :param records: list
    :return: list
    """

    fieldnames = []

    ordered_fieldname = (
        "time_last",
        "time_first",
        "source",
        "count",
        "bailiwick",
        "rrname",
        "rrtype",
        "rdata",
    )

    # build a list of unique keys from all returned records
    for record in records:
        keys = list(record.keys())
        for key in keys:
            if key not in fieldnames:
                fieldnames.append(key)

    # sort fieldnames based on order in ordered_fieldname
    fieldnames = sorted(fieldnames, key=lambda x: ordered_fieldname.index(x))

    return fieldnames