Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort dictionary by key length [duplicate]

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?

like image 381
Qiao Avatar asked Aug 01 '12 06:08

Qiao


1 Answers

>>> 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'
like image 67
jamylak Avatar answered Nov 16 '22 03:11

jamylak