Please help on this sorted function

Gary Herron gherron at digipen.edu
Tue Jun 2 17:00:00 EDT 2015


On 06/02/2015 01:20 PM, fl wrote:
> Hi,
>
> I try to learn sorted(). With the tutorial example:
>
>
>
>
>>>> ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
>>>> ff
> [1, 2, 3, 4, 5]
>
>
>
> I don't see what sorted does in this dictionary, i.e. the sequence of
> 1..5 is unchanged. Could you explain it to me?
>
>
> Thanks,

It's best to think of dictionaries as unordered collections of key/value 
pairs.  Dictionaries are not sequences, do not have any particular 
ordering, and in full generality *can't* be sorted in any sensible way.

For instance, this slightly odd (but perfectly legal) dictionary
     >>> d = {'a':123, 456:'b'}
can't be sorted
     >>> sorted(d)
     Traceback (most recent call last):
       File "<stdin>", line 1, in <module>
     TypeError: unorderable types: int() < str()
because it doesn't make sense to order/compare the two keys 'a' and 456.

If your dictionary is a little better behaved, say
     >>> d = {'a':123, 'b':456}
you may be able to sort the keys
     >>> sorted(d)
     ['a', 'b']
or the values
     >>> sorted(d.values())
     [123, 456]
or the key/value tuples (called items)
     >>> sorted(d.items())
     [('a', 123), ('b', 456)]
but each of those attempts to sort could fail on a general dictionary if 
the individual keys or values are not sortable.

There is also an implementation of a type of dictionary that remembers 
the order in which the items are *inserted*.  It's in the collections 
module and called OrderedDict.


Gary Herron






-- 
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list