Derek Fox
Derek Fox

Reputation: 11

How do you sort a list based on a dictionary key? Python

I have a dictionary

score={"basketball":[45,63],"baseball":[8,17],"football":[34,55],"soccer":[7,1]}

and a list

sports=["football","basketball","baseball","soccer"]

Is their a way to sort my list to match my dictionary like so

["basketball","baseball","football","soccer"]

Upvotes: 0

Views: 351

Answers (4)

Amitai Irron
Amitai Irron

Reputation: 2055

If your list has the same values as the key of the dictionary, why would you want to sort the list? Just take the keys of the dictionary, similar to what Renaud suggests:

sports = list(score)

If you are using a Python version that does not yet guarantee an order of dictionary entries, then of course the whole point is moot.

If you want some behavior for cases where the list of sports and the keys of scores are not the same (set-wise), then you should define that behavior.

Upvotes: 0

Samwise
Samwise

Reputation: 71454

Dictionaries are not ordered, so there is no ordering that will match the dictionary's ordering (it doesn't have one). You can observe this in the fact that two dictionaries specified with the same keys/values in different orders are considered equivalent:

Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> {'foo': True, 'bar': False} == {'bar': False, 'foo': True}
True

Given your example, the easiest fix would be to just initialize the list in the order you want to have it in, since these values are all hardcoded anyway. In a more complex example, the solution might be to either use an OrderedDict or to use a dict combined with a list that maintains the ordering.

Upvotes: 0

Lentian Latifi
Lentian Latifi

Reputation: 132

sort(score.keys())
sort(sports)

Try this and print both of them

Upvotes: 0

ForceBru
ForceBru

Reputation: 44838

You can convert the dictionary to a list of its keys and check a sport's index in this list:

>>> sorted(sports, key=lambda sport: list(score).index(sport))
['basketball', 'baseball', 'football', 'soccer']

Dictionaries are ordered since Python 3.7 (also see https://stackoverflow.com/a/39980744/4354477).

Upvotes: 1

Related Questions