user2492270
user2492270

Reputation: 2285

Sorting a LIST based on another DICTIONARY

I have a list and a dictionary:

list1 = ["a", "b", "c", "d"]

dict1 = 
{
    "a": 4,
    "b": 3,
    "c": 5,
    "d": 9,
    "e": 2,
    "f": 8
}


What I want to do is sort list1 according to the corresponding value in dict1.

FOr the above example, I want list to become ["b", "a", "c", "d"], sorted according to their values..

I know it should be something like...

list2 = sorted(list1, key=dict1[x])

But I am stuck :((

Any help will be really appreciated

Upvotes: 3

Views: 130

Answers (4)

falsetru
falsetru

Reputation: 369074

key argument should be a function.

For example, using bound method dict.__getitem__ or dict.get:

>>> list1 = ["a", "b", "c", "d"]
>>> dict1 = { "a": 4, "b": 3, "c": 5, "d": 9, "e": 2, "f": 8 }
>>> sorted(list1, key=dict1.__getitem__)
['b', 'a', 'c', 'd']

Upvotes: 5

dstromberg
dstromberg

Reputation: 7177

The key stuff others have suggested is remarkably powerful.

However, I guess the old timer in me is thinking "why not just put the data in a list of class instances and provide __lt__ and/or __cmp__?" IMO, it'd be much more clear.

Upvotes: 0

iruvar
iruvar

Reputation: 23364

I seem to have been beaten to the canonical solutions, so here's a different tack

from operator import itemgetter
[k for (k, v) in sorted(dict1.items(), key=itemgetter(1)) if k in list1]
['b', 'a', 'c', 'd']

Upvotes: 0

mdml
mdml

Reputation: 22882

You're super close. key takes a function; you need to wrap retrieving values from dict1 in a lambda (also pointed out by @falsetru):

>>> list2 = sorted(list1, key=lambda x: dict1[x])
>>> list2
 ['b', 'a', 'c', 'd']

Upvotes: 4

Related Questions