Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #65642 > unrolled thread
| Started by | Chris Angelico <rosuav@gmail.com> |
|---|---|
| First post | 2014-02-08 19:18 +1100 |
| Last post | 2014-02-08 19:18 +1100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Sorting dictionary by datetime value Chris Angelico <rosuav@gmail.com> - 2014-02-08 19:18 +1100
| From | Chris Angelico <rosuav@gmail.com> |
|---|---|
| Date | 2014-02-08 19:18 +1100 |
| Subject | Re: Sorting dictionary by datetime value |
| Message-ID | <mailman.6520.1391847492.18130.python-list@python.org> |
On Sat, Feb 8, 2014 at 7:03 PM, Frank Millman <frank@chagford.com> wrote:
> I am using python3. I don't know if that makes a difference, but I cannot
> get it to work.
>
>>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'}
>>>> sorted(d.items(), key=d.get)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: unorderable types: NoneType() < NoneType()
>>>>
You probably hadn't seen my subsequent post yet, in which I explain
what's going on here.
In Python 2, "None > None" is simply False. (So is "None < None",
incidentally.) Py3 makes that an error. But in all your examples,
you're effectively trying to sort the list [None, None, None], which
is never going to be useful. What you can do, though, is either sort
items using itemgetter to sort by the second element of the tuple, or
sort keys using dict.get.
Using 3.4.0b2:
>>> d = {1: 'abc', 2: 'xyz', 3: 'pqr'}
>>> sorted(d.keys(), key=d.get)
[1, 3, 2]
You don't get the values that way, but you get the keys in their
correct order, so you can iterate over that and fetch the
corresponding values. Alternatively, this is a bit more verbose, but
works on items():
>>> import operator
>>> sorted(d.items(), key=operator.itemgetter(1))
[(1, 'abc'), (3, 'pqr'), (2, 'xyz')]
operator.itemgetter(1) returns a callable that, when passed some
object, returns that_object[1].
ChrisA
Back to top | Article view | comp.lang.python
csiph-web