【问题标题】:sort dictionary by key length [duplicate]按键长度对字典进行排序[重复]
【发布时间】:2012-08-01 06:37:58
【问题描述】:

可能重复:
Dictionary sorting by key length

我需要使用字典进行“搜索和替换”。我希望它首先使用最长的键。

这样

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

应该返回“3x”,而不是现在的“22”。

有点像

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

只是无法得到里面的东西。
可以一串做吗?

【问题讨论】:

  • dict 对字典来说是一个非常糟糕的名字,你在隐藏内置,
  • python - Dictionary Sorting by Key Length -->在您提问前 5 分钟发布
  • 我和它没有任何联系)所以,sorted(d.iteritems(), key=lambda x: len(x[0])) 似乎是一个答案。
  • @Qiao 因为你不需要有序字典,所以我采用了不同的方法,只是对看起来更好的键进行排序 imo

标签: python dictionary


【解决方案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'

【讨论】:

  • @Qiao 嗯,它和你几乎拥有的key=lambda k: len(k) 一样,在这种情况下不需要lambda,但也许这样更清楚:)
  • 我从来没有见过len没有争论。
  • @Qiao 使用键作为参数调用它,因为sorted 遍历字典键并在每个字典键上调用key 函数进行排序。 sorted(d, key=d.get) 是我喜欢的另一个 sn-p,它按字典的值对字典进行排序,因为 d.get 是用每个键作为参数调用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 2014-08-02
  • 2013-05-27
  • 1970-01-01
  • 2022-11-18
相关资源
最近更新 更多