Yong Cui
Mar 16, 2021

--

By default, Python sorts items alphabetically. If seasons only use strings, the expected order won't work. We'll have to use a different data type, such as dictionary.

A possible solution is below:

seasons_mapped = {4: 'winter', 1: 'spring', 2: 'summer', 3: 'fall'}

seasons_sorted = [x[1] for x in sorted(seasons_mapped.items())]

seasons_sorted

['spring', 'summer', 'fall', 'winter']

--

--

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

No responses yet