my_dict = {1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'} # dict.items() returns an iterator that returns pairs of (key, value) pairs # the key argument to sorted tells sorted what to sort by, operator.itemgetter is a factory function , itemgetter(1)== lambda iterable: iterable[1] sorted_dict = sorted(my_dict.items(), key=itemgetter(1))
# at this moment sorted dict is a generator of key-value tuples in the right order sorted_dict = OrderedDict(sorted_dict) # turn the generator in to an actual dict. # notice: regular dicts are NOT ORDERED, you need a special type of dict to preserve the order, hence OrderedDict
-- https://mail.python.org/mailman/listinfo/python-list