python使用字符串列表作为值创建字典

cmc*_*eth 3 python dictionary list

我确信这可以做到,但到目前为止我没有成功:

我有一个字符串列表.我想创建一个字典,其中所述字符串的长度(可以表示为范围)作为键,字符串本身作为值.

例子:这里有类似我的清单:['foo','bar','help','this','guy']

我想最终得到这样的字典:{3:['foo','bar','guy],4:['this','help']}

Mar*_*ius 6

使用,defaultdict这样您就不必检查是否为新密钥创建列表:

from collections import defaultdict

x = ['foo','bar','help','this','guy']

len_dict = defaultdict(list)

for word in x:
    len_dict[len(word)].append(word)

len_dict
#
# Out[5]: defaultdict(list, {3: ['foo', 'bar', 'guy'], 4: ['help', 'this']})
Run Code Online (Sandbox Code Playgroud)