Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #91922
| Date | 2015-06-02 14:00 -0700 |
|---|---|
| From | Gary Herron <gherron@digipen.edu> |
| Subject | Re: Please help on this sorted function |
| References | <37d9de72-b719-45a0-976c-441fc5898741@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.91.1433315375.13271.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Please help on this sorted function fl <rxjwg98@gmail.com> - 2015-06-02 13:20 -0700
Re: Please help on this sorted function fl <rxjwg98@gmail.com> - 2015-06-02 13:25 -0700
Re: Please help on this sorted function Joonas Liik <liik.joonas@gmail.com> - 2015-06-02 23:42 +0300
Re: Please help on this sorted function Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-06-03 18:21 +1000
Re: Please help on this sorted function Chris Angelico <rosuav@gmail.com> - 2015-06-03 10:01 +1000
Re: Please help on this sorted function Joonas Liik <liik.joonas@gmail.com> - 2015-06-02 23:32 +0300
Re: Please help on this sorted function Gary Herron <gherron@digipen.edu> - 2015-06-02 14:00 -0700
csiph-web