Please help on this sorted function

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Jun 3 04:21:08 EDT 2015


On Wednesday 03 June 2015 06:42, Joonas Liik wrote:

> 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

OrderedDicts preserve the *insertion order*, they don't sort the keys.


Ordinary dicts are unordered. The order you see is arbitrary and 
unpredictable:

py> d = {}
py> d['C'] = 1; d['A'] = 2; d['B'] = 3
py> d
{'A': 2, 'C': 1, 'B': 3}


Ordered dicts are ordered by insertion order:

py> from collections import OrderedDict
py> d = OrderedDict()
py> d['C'] = 1; d['A'] = 2; d['B'] = 3
py> d
OrderedDict([('C', 1), ('A', 2), ('B', 3)])


Python doesn't have a SortedDict, where the keys are kept in sorted order.



-- 
Steve




More information about the Python-list mailing list