12

Possible Duplicate:
Dictionary sorting by key length

I need to use dictionary for "search and replace". And I want that first it use longest keys.

So that

text = 'xxxx'
dict = {'xxx' : '3','xx' : '2'} 
for key in dict:
    text = text.replace(key, dict[key])

should return "3x", not "22" as it is now.

Something like

for key in sorted(dict, ???key=lambda key: len(mydict[key])):


1つの文字列で実行することは可能ですか?

4

1 に答える 1

29
>>> text = 'xxxx'
>>> d = {'xxx' : '3','xx' : '2'}
>>> for k in sorted(d, key=len, reverse=True): # Through keys sorted by length
        text = text.replace(k, d[k])


>>> text
'3x'
于 2012-08-01T06:48:26.903 に答える