12
votes

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])):

Just can't get what is inside.
Is it possible to do in one string?

1
dict is a very bad name for a dictionary, you are shadowing the built-in, - jamylak
python - Dictionary Sorting by Key Length -->posted 5 minutes before your question - elssar
I have no connection with it ) So, sorted(d.iteritems(), key=lambda x: len(x[0])) is seems like an answer. - Qiao
@Qiao Since you don't need an ordered dictionary I took a different approach, just sorting the keys which looks nicer imo - jamylak

1 Answers

29
votes
>>> 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'