Lets say I want to sort a list that looks like this:
arr = ['45621', '78124', '24613']
The above list stores the IDs for various employees at a company. I don't want to sort based on the IDs alone, but based on attributes that correspond to the IDs, using the following dictionary:
d = {
'45621' : { 'rating' : 3, 'hours_worked' : 42 },
'78124' : { 'rating' : 4, 'hours_worked' : 78 },
'24613' : { 'rating' : 3, 'hours_worked' : 51 }
}
So its something like this: if an employee has a higher rating
, his/her ID will come first. However, if 2 employees have the same rating
, then we compare the hours_worked
, and whoever has worked more will come before the other.
I want to implement an insertion sort myself. Right now, my code looks like this:
def insertionSort(arr):
for i in range(1, len(arr)):
key = d[arr[i]]['rating']
second_key = d[arr[i]]['hours_worked']
j = i - 1
while j >= 0 and key < d[arr[j]]['rating']:
arr[j+1] = arr[j]
j -= 1
d[arr[j+1]]['rating'] = key
return arr
I cant seem to use the second key for comparisons. And moreover, this simply does not work. Any help?
Please note, I cannot change the nature of the input and the dictionary, and please no answers using the built-in methods.