user776942
user776942

Reputation:

Why does sorting this list of dicts fail when I change the order of the keys?

I have a list of dicts I am sorting. Why does the first method pass but the second fails? The python docs don't address this (or I'm just missing something totally obvious).

listy = []
listy.append({'a':None,'b':'Fred'})
listy.append({'a':datetime.now().date(),'b':'Dave'})

listy.sort(key=lambda k:(k['b'],k['a'])) # o.k.
listy.sort(key=lambda k:(k['a'],k['b'])) # fails with "TypeError: can't compare datetime.date to NoneType"

Upvotes: 0

Views: 95

Answers (2)

Matimus
Matimus

Reputation: 512

It is comparing tuples element by element. It will only compare the second elements if the first ones are equal. In other words, it would fail if both 'b' values were set to 'Dave'.

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304473

In the first case you are comparing the tuples

('Fred', None) < ('Dave', datetime.now().date())

Since the first element of each tuple is different, Python doesn't need to compare the second element at all to know which one is less than the other.

In the second case you are comparing None to a date. Python2 did allow mixed type comparisons (though not this specific case - see the comments), but it wasn't particularly useful and is more likely to cause strange bugs, so this ability was removed in Python3

Upvotes: 4

Related Questions