Sorting dictionary keys by values in a list?

dictionary, list, python, sorting

Solution

You shouldn't call you variables dict and list, because then, you cant use the build-in methods any more. I have renamed them in this example.

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

Note that prior to Python 3.7 you could not sort dictionaries in Python (they were hash tables sorted by the hash functions of the keys). Alternative dictionary implementations existed to work around this (`OrderedDict`).

But you can create a new list containing the (key, value)-tuples from any dictionary, which is sorted by the first list:

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

Or if you are only interested in the values:

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

Hope that helps!

Problem

I have a dictionary and a list. The values of the keys match those of the list, I'm just trying to find out how to sort the values in the dictionary by the values in the list. ``` >>> l = [1, 2, 37, 32, 4, 3] >>> d = { 32: 'Megumi', 1: 'Ai', 2: 'Risa', 3: 'Eri', 4: 'Sayumi', 37: 'Mai' } ``` I've tried using something along the lines of... ``` >>> sorted(dict.keys(), key=list.index) ``` ... but obviously that only returns the keys in the desired order. (Should have realized at 3AM that `list` and `dict` were horrible names, I changed them to `l` and `d` accordingly.)

Original source