Skip to content Skip to sidebar Skip to footer

Sort Dictionary By Key Length

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 =

Solution 1:

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

Post a Comment for "Sort Dictionary By Key Length"