Search code examples
pythondictionaryinsertion-sort

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)

this is my output after i run my codes

these are my codes and i have been trying to sort my dictionary using insertion sort but i keep running into this error and have no idea what to.

i would like my output to be a list of unsorted dictionary followed by a list of the sorted dictionary

i would appreciate any help i can get thank you in advance


Solution

  • Dicts are not sequences (although they preserve insertion order in Python 3.7+). You can convert it to a list:

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

    ... But apparently your algorithm doesn't work, since this is the output:

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