Order in Python

Effective ways to avoid chaos

Introduction

###################  collections used in this post  ################
>>> numbers = [19, 223, 2, 31, 45, 6, 12, -11, 121, 27, 38]
>>> colours = ['purple', 'red', 'blue', 'green', 'yellow']
>>> doors = dict(zip(numbers, colours))

>>> bubblesort(numbers)
[-11, 2, 6, 12, 19, 27, 31, 38, 45, 121, 223])
>>> 'b' > 'a'
True
>>> bubblesort(colours)
['blue', 'green', 'purple', 'red', 'yellow']

Built-in Functions

How fast are the built in functions?

>>> %%timeit
>>> bubblesort(numbers)
[-11, 2, 6, 12, 19, 27, 31, 38, 45, 121, 223]
5.9 µs ± 897 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
>>> %%timeit
>>> sorted(numbers)
[-11, 2, 6, 12, 19, 27, 31, 38, 45, 121, 223]
165 ns ± 2.65 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
>>> %%timeit
>>> [numbers].sort()
>>> numbers
[-11, 2, 6, 12, 19, 27, 31, 38, 45, 121, 223]
77.8 ns ± 0.698 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

The arguments

>>> sorted(numbers, reverse=True)
[223, 121, 45, 38, 31, 27, 19, 12, 6, 2, -11]
>>> sorted(colours, key=len)
['red', 'blue', 'green', 'purple', 'yellow']
>>> sorted(numbers, key=lambda x: x*x)
[2, 6, -11, 12, 19, 27, 31, 38, 45, 121, 223]
>>> pangram = "The quick brown fox jumps over the lazy dog">>> sorted(pangram.split(), key=str.lower)
['brown', 'dog', 'fox', 'jumps', 'lazy', 'over', 'quick', 'The', 'the']
>>> from functools import cmp_to_key >>> def chicken_or_egg(a, b): 
... if a[-1] > b[-1]:
... return 1
... elif a[-1] < b[-1]:
... return -1
... else:
... return 0
>>> sorted(colours, key = cmp_to_key(chicken_or_egg))
['red', 'blue', 'purple', 'green', 'yellow']
>>> sorted(doors)
[2, 19, 31, 45, 223]
>>> sorted(doors.items())
[(2, 'blue'), (19, 'purple'), (31, 'green'), (45, 'yellow'), (223, 'red')]
>>> sorted(doors.values())
['blue', 'green', 'purple', 'red', 'yellow']
>>> sorted(doors.items(), key=lambda x:x[1])
[(2, 'blue'), (31, 'green'), (19, 'purple'), (223, 'red'), (45, 'yellow')]
>>> doors
{19: 'purple', 223: 'red', 2: 'blue', 31: 'green', 45: 'yellow'}
>>> data = [{"number":19, "colour":'purple'},
... {"number":223, "colour":'red'},
... {"number":2, "colour":'blue'},
... {"number":31, "colour":'green'},
... {"number":45, "colour":'yellow'}
... ]
>>> sorted(data, key=lambda x: x['colour'])
[{'number': 2, 'colour': 'blue'},
{'number': 31, 'colour': 'green'},
{'number': 19, 'colour': 'purple'},
{'number': 223, 'colour': 'red'},
{'number': 45, 'colour': 'yellow'}]

Final Thoughts

>>> from collections import OrderedDict>>> OrderedDict(sorted(doors.items(), key=lambda x:x[1]))
OrderedDict([(2, 'blue'),
(31, 'green'),
(19, 'purple'),
(223, 'red'),
(45, 'yellow')])

Useful Links

Data Scientist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store