strtr do php para python

php tem ostrtr função:

strtr('aa-bb-cc', array('aa' => 'bbz', 'bb' => 'x', 'cc' => 'y'));
# bbz-x-y

Ele substitui as chaves de dicionário em uma string por valores correspondentes e (importante) não substitui as strings já substituídas. Uma tentativa ingênua de escrever o mesmo em python:

def strtr(strng, replace):
    for s, r in replace.items():
        strng = strng.replace(s, r)
    return strng

strtr('aa-bb-cc', {'aa': 'bbz', 'bb': 'x', 'cc': 'y'})

devolvexz-x-y o que nós não queremosbb foi substituído novamente). Como mudar a função acima para que ela se comporte como sua contraparte PHP?

(Eu preferiria uma resposta sem expressões regulares, se possível).

Upd: algumas ótimas respostas aqui. Eu cronometrá-los e descobri que para as cordas curtas a versão de Gumbo parece ser a mais rápida, em cordas mais longas o vencedor é ore solução:

# 'aa-bb-cc'
0.0258 strtr_thg
0.0274 strtr_gumbo
0.0447 strtr_kojiro
0.0701 strtr_aix

# 'aa-bb-cc'*10
0.1474 strtr_aix
0.2261 strtr_thg
0.2366 strtr_gumbo
0.3226 strtr_kojiro

Minha própria versão (que é um pouco otimizada do Gumbo):

def strtr(strng, replace):
    buf, i = [], 0
    while i < len(strng):
        for s, r in replace.items():
            if strng[i:len(s)+i] == s:
                buf.append(r)
                i += len(s)
                break
        else:
            buf.append(strng[i])
            i += 1
    return ''.join(buf)

Códigos completos e horários:https://gist.github.com/2889181

questionAnswers(5)

yourAnswerToTheQuestion