I have a list of dictionaries with various keys, all of which are integers, and I need to write a function which uses insertion sort to sort them by the specific key.
def insertionsort(alldata, key):
for i in alldata :
temp = alldata[i]
j = i
while j > 0 and alldata[i['key']] < alldata[j - 1['key']]: # no idea how to put this
alldata[j] = alldata[j-1]
alldata[j] = temp
i['key']
looks like mistake. You aren't using your key
variable here.
Try alldata[i][key] < alldata[j - 1][key]
as a condition
Also you need to change j
in your while loop or it can ran forever
def insertionsort(alldata, key):
for i in alldata :
temp = alldata[i]
j = i
while j > 0 and alldata[i][key] < alldata[j - 1][key]:
alldata[j] = alldata[j - 1]
j -= 1
alldata[j] = temp
Every thing after the for loop shuld be indented 1 more time (whatever number of spaces you use for indenting)
As for any other issues, I dont know.