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?
dictis a very bad name for a dictionary, you are shadowing the built-in, - jamylaksorted(d.iteritems(), key=lambda x: len(x[0]))is seems like an answer. - Qiao