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?
>>> 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With