def generate_linkage(dist_mat, max_dist):
    """
    Create a nested dictionary linking genomes if their distance is within
    a certain threshold.

    :param dist_mat: pandas DataFrame with distances
    :param max_dist: maximum allowed distance to link genomes
    :return: a nested dictionary
    """
    linkage = {}
    for i in range(len(dist_mat.index)):
        g1 = dist_mat.index[i]
        if not g1 in linkage.keys():
            linkage[g1] = {}
        for j in range(i + 1, len(dist_mat.columns)):
            g2 = dist_mat.columns[j]
            if not g2 in linkage.keys():
                linkage[g2] = {}
            distance = dist_mat.iloc[i, j]
            if distance <= max_dist:
                linkage[g1][g2] = ""
                linkage[g2][g1] = ""
    return linkage