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

Bry*_*oso 3 python sorting dictionary list

我有一本字典和一份清单.键的值与列表的值匹配,我只是想知道如何通过列表中的值对字典中的值进行排序.

>>> l = [1, 2, 37, 32, 4, 3]
>>> d = {
    32: 'Megumi', 
    1: 'Ai',
    2: 'Risa',
    3: 'Eri', 
    4: 'Sayumi', 
    37: 'Mai'
}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用的东西......

>>> sorted(dict.keys(), key=list.index)
Run Code Online (Sandbox Code Playgroud)

...但显然只返回所需顺序的键.

(应该在凌晨3点已经实现了listdict是可怕的名字,我把它们改成ld相应的.)

Joh*_*ooy 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')]
>>>
Run Code Online (Sandbox Code Playgroud)


tux*_*21b 5

您不应该将变量称为 dict 和 list,因为这样您就无法再使用内置方法了。我在这个例子中对它们进行了重命名。

>>> l = [1, 2, 37, 32, 4]
>>> d = dict = {
...     32: 'Megumi', 
...     1: 'Ai',
...     2: 'Risa',
...     3: 'Eri', 
...     4: 'Sayumi', 
...     37: 'Mai'
... }
Run Code Online (Sandbox Code Playgroud)

请注意,在 Python 3.7 之前,您无法对 Python 中的字典进行排序(它们是按键的哈希函数排序的哈希表)。存在替代的字典实现来解决这个问题(OrderedDict)。

但是您可以创建一个包含任何字典中的(键,值)元组的新列表,该列表按第一个列表排序:

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

或者,如果您只对值感兴趣:

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

希望有帮助!