print consensensus sequences for each genome and sample

def print_consensus(genomes):
    """
    print consensensus sequences for each genome and sample
    """
    # generate consensus sequences
    cons = {} # cons[genome][sample][contig] = consensus
    for genome, contigs in list(genomes.items()):
        cons[genome] = {}
        for contig, samples in list(contigs.items()):
            for sample, stats in list(samples.items()):
                if sample not in cons[genome]:
                    cons[genome][sample] = {}
                seq = cons[genome][sample][contig] = []
                for pos, ps in enumerate(stats['bp_stats'], 1):
                    ref, consensus = ps['ref'], ps['consensus'][0]
                    if consensus == 'n/a':
                        consensus = ref.lower()
                    seq.append(consensus)
    # print consensus sequences
    for genome, samples in cons.items():
        for sample, contigs in samples.items():
            fn = '%s.%s.consensus.fa' % (genome, sample)
            f = open(fn, 'w')
            for contig, seq in contigs.items():
                print('>%s' % (contig), file = f)
                print(''.join(seq), file = f)
            f.close()
    return cons