Please help on this sorted function

Joonas Liik liik.joonas at gmail.com
Tue Jun 2 16:42:31 EDT 2015


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150602/993e0e7e/attachment.html>


More information about the Python-list mailing list