按键长度排序字典 [英] sort dictionary by key length

查看:208
本文介绍了按键长度排序字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

按密钥长度排序的字典

我需要使用字典用于搜索和替换。而我首先要使用最长的钥匙。

I need to use dictionary for "search and replace". And I want that first it use longest keys.

所以

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

应该返回3x,而不是22。

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

某些东西像

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?

推荐答案

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

这篇关于按键长度排序字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆