An easy approach to sorting objects by a key without using a key function is to sort the objects by a tuple order, where each tuple consists of all the relevant keys and the object itself:
import bisect
from collections import namedtuple
Order = namedtuple('Order', ('item', 'price', 'timestamp'))
orders = [
Order('banana', 2, 5),
Order('apple', 4, 3),
Order('orange', 2, 4),
Order('mango', 1, 7),
Order('guava', 3, 1)
]
my_list = []
for count, order in enumerate(orders, 1):
print(f'Insertion #{count}')
bisect.insort_right(my_list, (order.price, order.timestamp, order))
for _, _, order in my_list:
print(order)
print()
This outputs:
Insertion #1
Order(item='banana', price=2, timestamp=5)
Insertion #2
Order(item='banana', price=2, timestamp=5)
Order(item='apple', price=4, timestamp=3)
Insertion #3
Order(item='orange', price=2, timestamp=4)
Order(item='banana', price=2, timestamp=5)
Order(item='apple', price=4, timestamp=3)
Insertion #4
Order(item='mango', price=1, timestamp=7)
Order(item='orange', price=2, timestamp=4)
Order(item='banana', price=2, timestamp=5)
Order(item='apple', price=4, timestamp=3)
Insertion #5
Order(item='mango', price=1, timestamp=7)
Order(item='orange', price=2, timestamp=4)
Order(item='banana', price=2, timestamp=5)
Order(item='guava', price=3, timestamp=1)
Order(item='apple', price=4, timestamp=3)
So that each insertion takes only an average time complexity of O(n) as opposed to O(n log n) if you had used the sort
method.