用字典插入排序

insertion sort with dictionary

stock={'meat':100,'fish':50,'bread':70, 'milk':35,'chips':15, 'apple':10,'orange':10, 'rice':10,'honey':10,'lemon':10}

def insertionSort( theSeq ):
    n = len( theSeq )

    for i in range(1, n):
       key = theSeq[i]
       pos = i
       while pos > 0 and key < theSeq[pos - 1]:
           theSeq[pos] = theSeq[pos-1]
           pos -= 1

    theSeq[pos] = key


print('Input List:', stock)
insertionSort(stock)
print('Sorted List:', stock)

这些是我的代码,我一直在尝试使用插入排序对我的字典进行排序,但我一直 运行 进入此错误并且不知道该怎么做。

我希望我的输出是一个未排序字典列表,后跟一个已排序字典列表

如果能得到任何帮助,我将不胜感激 提前谢谢你

字典不是序列(尽管它们在 Python 3.7+ 中保留插入顺序)。您可以将其转换为列表:

L = list(stock.items())
insertionSort(L)
print(L)

...但显然你的算法不起作用,因为这是输出:

[('lemon', 10), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('meat', 100), ('milk', 35), ('orange', 10), ('rice', 10)]