我正在嘗試按值對字典進行排序,其中我的每個鍵都有很多值。我知道不可能對字典進行排序,只能獲得已排序字典的表示形式。字典本質上是無序的。
我在另一篇文章中嘗試了這個解決方案,但它似乎不適用于我的情況:
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} {k: v for k, v in sorted(x.items(), key=lambda item: item[1])} {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
或者
dict(sorted(x.items(), key=lambda item: item[1])) {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
從這篇文章 如何按值對字典進行排序?
另外,我試過:
sorted(x, key=lambda x: x['key'])
但是,我的 dict 是一個字串,它不起作用,如果我想在每個鍵中應用它,這不是最好的選擇,我必須為每個鍵重復這個程序。
這是我的 dict 示例:
{
'/Users/01':
['V01File12.txt',
'V01File01.txt',
'V01File18.txt',
'V01File15.txt',
'V01File02.txt',
'V01File11.txt' ] ,
'/Users/02':
['V02File12.txt',
'V02File01.txt',
'V02File18.txt',
'V02File15.txt',
'V02File02.txt',
'V02File11.txt' ]
}
等等 ...
預期的輸出將是:
{'/Users/01':
['V01File01.txt',
'V01File02.txt',
'V01File11.txt',
'V01File12.txt',
'V01File15.txt',
'V01File18.txt' ] ,
'/Users/02':
['V02File01.txt',
'V02File02.txt',
'V02File11.txt',
'V02File12.txt',
'V02File15.txt',
'V02File18.txt' ]
}
uj5u.com熱心網友回復:
因此,您不是在嘗試對字典進行排序,而是在嘗試對其中的串列進行排序。我只會使用一個理解:
data = {k, sorted(v) for k, v in data.items()}
或者只是改變 dict 到位:
for v in data.values():
v.sort()
uj5u.com熱心網友回復:
如果要對每個字典中的串列進行排序:
a ={
'/Users/01':
['V01File12.txt',
'V01File01.txt',
'V01File18.txt',
'V01File15.txt',
'V01File02.txt',
'V01File11.txt' ] ,
'/Users/02':
['V02File12.txt',
'V02File01.txt',
'V02File18.txt',
'V02File15.txt',
'V02File02.txt',
'V02File11.txt' ]
for i in a:
a[i] = sorted(a[i])
uj5u.com熱心網友回復:
最好的解決方案是@StevenRumblaski 的解決方案:
for b in a.values(): b.sort()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510500.html
標籤:Python排序字典
下一篇:排序和顯示特定列
