我有一本字典和一个列表。键的值与列表的值匹配,我只是想找出如何根据列表中的值对字典中的值进行排序。
>>> 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')]
>>>
关于python - 按列表中的值对字典键进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2257101/