strLst = [‘Insert’, ‘key’,‘with’,‘a’,‘value’,‘of’,‘default’,‘if’,‘key’,‘is’,‘not’,‘in’,‘the’,‘dictionary’]
strLst.sort()
d={}
for word in strLst:
d.setdefault(len(word), []).append(word) #Insert key with a value of default if key is not in the dictionary.
for key in sorted(d):
print ("%s: %s" % (key, d[key]))
输出结果:
1: [‘a’]
2: [‘if’, ‘in’, ‘is’, ‘of’]
3: [‘key’, ‘key’, ‘not’, ‘the’]
4: [‘with’]
5: [‘value’]
6: [‘Insert’]
7: [‘default’]
10: [‘dictionary’]