Search code examples
pythondictionarykey-valuebubble-sort

bubble sorting in dictionary in python


I am trying to do bubble sort in descending order

input={"m":1,"i":4,"s":4,"P":2}

output={"i":4,"s":4,"p":2,"m":1}

but a type error occurs. How can I do this?

Below is the code:

dict={"m":1,"i":4,"s":4,"P":2}
for key,value in dict.items():
    if(dict[key]<dict[key+1]):
        temp=dict[key]
        dict[key]=dict[key+1]
        dict[key+1]=temp
print(dict)        

Solution

  • A dictionary has no order: if you add/remove/update elements in a dictionary, the order in which the keys are iterated can change.

    So you can not "sort" a dictionary. What you can do however, is for example sort a list of 2-tuples, like:

    my_list = list(my_dict.items())
    

    We then retrieve:

    >>> my_list
    [('m', 1), ('i', 4), ('s', 4), ('P', 2)]
    

    and thnen we can sort the list (for example with bubblesort) like:

    for mx in range(len(my_list)-1, -1, -1):
        swapped = False
        for i in range(mx):
            if my_list[i][1] < my_list[i+1][1]:
                my_list[i], my_list[i+1] = my_list[i+1], my_list[i]
                swapped = True
        if not swapped:
            break
    

    Then afterwards, we have:

    >>> my_list
    [('i', 4), ('s', 4), ('P', 2), ('m', 1)]