0

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"]
Derek Fox
  • 11
  • 3

4 Answers4

1

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).

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • 1
    Dictionaries [are ordered since Python 3.7](https://docs.python.org/3.7/whatsnew/3.7.html): "the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec" – ForceBru May 04 '20 at 20:44
0
sort(score.keys())
sort(sports)

Try this and print both of them

ForceBru
  • 43,482
  • 10
  • 63
  • 98
0

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.

Amitai Irron
  • 1,973
  • 1
  • 12
  • 14