[Solved] Python: Sort dictionary by value (equal values)


dictionaries are unordered (well pre 3.6 at least), instead sort the items

d = {3: '__init__', 5: 'other', 7: 'hey  ', 11: 'hey'}
print(sorted(d.items(),key=lambda item:(item[0].strip(),item[1])))

# output => [(3, '__init__'), (7, 'hey  '), (11, 'hey'), (5, 'other')]

if you really want it as a dict (for reasons i cant fathom) and you are using 3.6+ then you can just create a new dict from your sorted items

d2 = dict(sorted(d.items(),key=lambda item:item[1]))

*(note that in 3.6 that dicts maintain order is an implementation detail, not a guarantee, but 3.7+ its part of the language specification)

you can do the same thing in earlier pythons using collections.OrderedDict

from collections import OrderedDict
d2 = OrderedDict(sorted(d.items(),key=lambda item:item[1]))

since you cant use builtin sorted here is a bubble sort for you … although I dont understand how having strangers on the internet write a sort function for you is any better than just using the python builtin sorted

def my_bubble_sort(list_thing,key_fn):
    # sort a list in place by a key fn
    changed = True
    while changed:
        changed = False
        for i in range(len(list_thing)-1):
            if key_fn(list_thing[i]) > key_fn(list_thing[i+1]):
               list_thing[i],list_thing[i+1] = list_thing[i+1],list_thing[i]
               changed = True

d = {3: '__init__', 5: 'other', 7: 'hey  ', 11: 'hey'}
d_list = d.items()
my_bubble_sort(d_list,lambda item:(item[1].strip(),item[0]))
print(d_list)

5

solved Python: Sort dictionary by value (equal values)