from collections import defaultdict


def difreq(seq):
    """
    Does di-nucleotide shuffling of sequences, preserving the frequences.
    Code found here:
    https://www.biostars.org/p/66004/

    """
    counts = defaultdict(lambda: defaultdict(int))
    for a, b in zip(seq, seq[1:]):
        counts[a][b] += 1
    return dict((k, dict(v)) for k,v in counts.items())