按列表中的值对字典键进行排序?

时间:2010-02-13 09:41:07

标签: python list sorting dictionary

我有一本字典和一份清单。键的值与列表的值匹配,我只是想了解如何按列表中的值对字典中的值进行排序。

>>> 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。)

5 个答案:

答案 0 :(得分: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')]
>>>

答案 1 :(得分:4)

你不应该叫你变量dict和list,因为那时你不能再使用内置方法了。我在这个例子中重命名了它们。

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

你不能在Python中对默认的dict类型进行排序,因为它是一个哈希表,因此按键的哈希函数排序。无论如何,当你在谷歌中搜索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']

希望有所帮助!

答案 2 :(得分:1)

您无法对字典进行排序,因为未对字典进行排序。

你能做的是:

  • 从字典中获取所有键值对,对它们进行排序并将它们放入列表或
  • 您正在做的事情:保留已排序的键列表,并在需要与键对应的值时使用词典。

答案 3 :(得分:0)

Sorted 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)]

答案 4 :(得分: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')])
相关问题