我有一个字符串来分类吧...如何把我的字典值类{}改为[]和键
my_string="The way you see people is the way you treat them and the Way you treat them is what they become"
我DEF应该返回此:
{2: ['is'],
3: ['and', 'see', 'the', 'way', 'you'],
4: ['them', 'they', 'what'],
5: ['treat'],
6: ['become', 'people']}
我的解决方案回报:
{3: {'you', 'see', 'way', 'and', 'the'},
6: {'become', 'people'},
2: {'is'},
5: {'treat'},
4: {'what', 'them', 'they'}}
我需要通过排序键和变化值的类字典...我的价值类是{},但我想[] 我解决方案:
def n_letter_dictionary(my_string):
my_string=my_string.lower().split()
sample_dictionary={}
r=[]
for word in my_string:
lw=len(word)
if lw in sample_dictionary:
sample_dictionary[lw].add(word)
else:
sample_dictionary[lw] = {word}
return sample_dictionary
print(n_letter_dictionary("The way you see people is the way you treat them
and the Way you treat them is what they become"))
我怎么能做到这一点任何人都可以帮助吗?
字典无法排序。它们是非结构化数据容器(至少达到Python 3.6)。将'set'转换为'list'很简单 –
['collections.OrderedDict'](https://docs.python.org/3/library/collections.html#collections.OrderedDict)会返回右边的项目订单,但我不确定它将如何打印。你还需要像'return OrderedDict(sorted(sample_dictionary.items(),key = lambda x:x [0]))'' – Kendas