Sort dictionary by key length

Possible duplicate:
Sort dictionary by key length

I need to use a dictionary for search and replace. And I want the longest keys to be used first.

So,

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

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

Sort of

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

I just can’t get what is inside.
Is it possible to do in one line?

+6
source share
1 answer
 >>> 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' 
+14
source

Source: https://habr.com/ru/post/921823/


All Articles