def getClusterMembers(Z):
    """Generate dict of lists where each key is a cluster ID from the results
    of linkage-based hierarchical clustering with scipy.cluster.hierarchy.linkage (Z)

    Parameters
    ----------
    Z : linkage matrix [clusters, 4]

    Returns
    -------
    members : dict of lists
        Each element has a cluster ID (key) and a list of
        cluster members (indices into the original data matrix)"""

    clusters = {}
    for i, merge in enumerate(Z):
        cid = 1 + i + Z.shape[0]
        clusters[cid] = [merge[0], merge[1]]

    def _getIndices(clusters, i):
        if i <= Z.shape[0]:
            return [int(i)]
        else:
            return _getIndices(clusters, clusters[i][0]) + _getIndices(clusters, clusters[i][1])

    members = {i:_getIndices(clusters, i) for i in range(Z.shape[0] + 1, max(clusters.keys()) + 1)}
    return members