Hi So I have a dictionary like this
a = {1 : ["", 4],
2 : ["", 2],
3 : ["", 8],
4 : ["", 1],
5 : ["", 20],
6 : ["", 3],
7 : ["", 2]}
I'm trying to sort this by a[key][1] which is the numbers in the list using the Insertion Sort Algorithm.
Here is my code for the Insertion Sort:
def insertionSort(inventory):
indexingRange = range(1, len(inventory))
for i in indexingRange:
x = inventory[i][1]
try:
while inventory[i-1][1] > x and i > 0:
inventory[i-1], inventory[i] = inventory[i], inventory[i-1]
i = i - 1
except KeyError:
pass
return inventory
However when I run this code, everything but the last element in the dictionary gets sorted.
So my output becomes like this:
{1: ['', 1],
2: ['', 2],
3: ['', 3],
4: ['', 4],
5: ['', 8],
6: ['', 20],
7: ['', 2]}
I have no idea what i'm doing wrong. I'm pretty sure it's an indexing issue but I can't seem to solve it. Can someone help out please. Thanks!