[英]Sorting dictionary keys by values in a list?
我有一本字典和一份清單。 鍵的值與列表的值匹配,我只是想知道如何通過列表中的值對字典中的值進行排序。
>>> 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點意識到list
和dict
是可怕的名字,我把它們改為l
和d
。)
不要遮蔽內置dict
和list
>>> 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')]
>>>
你不應該叫你變量dict和list,因為那時你不能再使用內置方法了。 我在這個例子中重命名了它們。
>>> l = [1, 2, 37, 32, 4]
>>> d = dict = {
... 32: 'Megumi',
... 1: 'Ai',
... 2: 'Risa',
... 3: 'Eri',
... 4: 'Sayumi',
... 37: 'Mai'
... }
你不能在Python中對默認的dict類型進行排序,因為它是一個哈希表,因此按鍵的哈希函數排序。 無論如何,當您在google中搜索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']
希望有所幫助!
您無法對字典進行排序,因為未對字典進行排序。
你可以做的是:
排序的dict實際上是一個2元組的列表,因為在Python 2.x中沒有內置的有序dictionat。 您幾乎得到了解決方案,只需在排序鍵后添加值查找:
[(k,dict[k]) for k in sorted(dict.keys(), key=list.index)]
但是當密鑰不在list
時,這會失敗。 讓我們添加一個修改,將所有這些值放在sort的末尾,按值排序:
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)]
在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')])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.