我有一個字符串來分類吧...如何把我的字典值類{}改爲[]和鍵
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