13

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?

Community
  • 1
  • 1
Qiao
  • 16,565
  • 29
  • 90
  • 117
  • 4
    `dict` is a very bad name for a dictionary, you are shadowing the built-in, – jamylak Aug 01 '12 at 06:40
  • 1
    [python - Dictionary Sorting by Key Length](http://stackoverflow.com/questions/11753758/dictionary-sorting-by-key-length) -->posted 5 minutes before your question – elssar Aug 01 '12 at 06:44
  • I have no connection with it ) So, `sorted(d.iteritems(), key=lambda x: len(x[0]))` is seems like an answer. – Qiao Aug 01 '12 at 06:46
  • @Qiao Since you don't need an ordered dictionary I took a different approach, just sorting the keys which looks nicer imo – jamylak Aug 01 '12 at 06:52

1 Answers1

30
>>> 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'
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • 3
    @Qiao Well it's that same as `key=lambda k: len(k)` which you almost had, there is no need for `lambda` in this case but maybe that makes it clearer :) – jamylak Aug 01 '12 at 06:54
  • I've never seen `len` without argument. – Qiao Aug 01 '12 at 06:59
  • 1
    @Qiao It's called with the key as it's argument as `sorted` iterates through the dictionary keys and calls the `key` function on each dictionary key to sort by. `sorted(d, key=d.get)` is another snippet I like, it sorts the dictionary by it's values since `d.get` is called with each key as it's argument. – jamylak Aug 01 '12 at 07:03