2010-02-13 214 views
3

我有一本字典和一個列表。這些鍵的值與列表的值相匹配,我只是想了解如何按列表中的值對字典中的值進行排序。按列表中的值對字典鍵進行排序?

>>> l = [1, 2, 37, 32, 4, 3] 
>>> d = { 
    32: 'Megumi', 
    1: 'Ai', 
    2: 'Risa', 
    3: 'Eri', 
    4: 'Sayumi', 
    37: 'Mai' 
} 

我一直在使用的線沿線的東西試過......

>>> sorted(dict.keys(), key=list.index) 

......但顯然,只有返回所需的順序按鍵。

(應該在凌晨3點已經意識到listdict是可怕的名字,我把它們改成ld相應。)

+0

你有3作爲字典鍵,但它不是在列表中 – 2010-02-13 09:57:03

+0

哎呦,看起來像我忽略了。謝謝! – 2010-02-13 20:45:48

回答

4

你不應該叫你變量字典和列表,因爲那樣的話,你不能再使用內置的方法。在這個例子中,我已經重新命名了它們。

>>> l = [1, 2, 37, 32, 4] 
>>> d = dict = { 
...  32: 'Megumi', 
...  1: 'Ai', 
...  2: 'Risa', 
...  3: 'Eri', 
...  4: 'Sayumi', 
...  37: 'Mai' 
... } 

無法排序在Python默認的字典類型,因爲它是一個哈希表,因此由按鍵的散列函數來分類的。無論如何,當你在谷歌搜索OrderedDict或類似的東西時,你可能會發現一些替代Python的實現。

>>> s = list((i, d.get(i)) for i in L) 
>>> print s 
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')] 

或者如果你只對值感興趣:

但是你可以創建一個包含(鍵,值)一個新的列表從詞典,這是第一個列表排序的元組

>>> s = list(d.get(i) for i in L) 
>>> print s 
['Ai', 'Risa', 'Mai', 'Megumi', 'Sayumi'] 

希望有幫助!

+0

謝謝!因爲我剛剛意識到我確實不需要密鑰,所以我最終使用了第二種解決方案。 :) – 2010-02-13 21:24:01

1

您不能對一個字典,因爲字典是無序的。

你可以做的反而是:

  • 獲取所有的鍵 - 值對出的字典,對它們進行排序,並把它們放到一個列表或
  • 你已經在做什麼:保持整理當您需要與某個鍵相對應的值時,使用字典列表。
6

不要遮蔽內建dictlist

>>> L = [1, 2, 37, 32, 4, 3] 
>>> D = { 
...  32: 'Megumi', 
...  1: 'Ai', 
...  2: 'Risa', 
...  3: 'Eri', 
...  4: 'Sayumi', 
...  37: 'Mai' 
... } 

# Seems roundabout to use sorted here 
# This causes an index error for keys in D that are not listed in L 
>>> sorted(D.items(), key=lambda x:L.index(x[0])) 
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')] 
>>> 

# I think this is more direct than using sorted. 
# This also ignores/skips keys in D that aren't listed in L 
>>> [(i,D[i]) for i in L] 
[(1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi'), (3, 'Eri')] 
>>> 
0

排序字典事實上是2元組的列表,因爲在Python 2.x的存在是沒有下令dictionaty內置。你幾乎得到了解決,只需添加一個值查找排序鍵後:

[(k,dict[k]) for k in sorted(dict.keys(), key=list.index)] 

但是當鑰匙不在list失敗。讓我們添加的修改,把所有這些值在排序結束後,按值排序:

def _index(x): # Allow non-full key list to be used in sorting 
    try: return (list.index(x), x) 
    except ValueError: return (sys.maxint, x) 

[(k,dict[k]) for k in sorted(dict.keys(), key=_index)] 
0

在Python 3。1,你可以使用OrderedDict類:

from collections import OrderedDict 

l = [1, 2, 37, 32, 4] 
d = { 
    32: 'Megumi', 
    1: 'Ai', 
    2: 'Risa', 
    3: 'Eri', 
    4: 'Sayumi', 
    37: 'Mai' 
} 

def myindex(element): 
    try: 
     return l.index(element) 
    except ValueError: 
     return -1 # nonexisting keys are appended to the beginning of the list 

od = OrderedDict(sorted(d.items(), key = lambda t: myindex(t[0]))) 

print(od) 

,因爲我不知道你想與不在列表中的鍵做什麼,我只是返回-1在這種情況下,這意味着這些元素以某種方式預先列入清單(即以非穩定的順序)。

我的示例將打印

OrderedDict([(3, 'Eri'), (1, 'Ai'), (2, 'Risa'), (37, 'Mai'), (32, 'Megumi'), (4, 'Sayumi')]) 
相關問題