Sorting dictionary by datetime value

Frank Millman frank at chagford.com
Sun Feb 9 01:48:23 EST 2014


"Peter Otten" <__peter__ at web.de> wrote in message 
news:ld4pon$ni9$1 at ger.gmane.org...
> Frank Millman wrote:
>
> Here you can watch the key calculation at work:
>
>>>> d = {'1': 'abc', '2': 'xyz', '3': 'pqr'}
>>>> def sortkey(value):
> ...     key = d.get(value)
> ...     print "value:", value, "sort-key:", key
> ...     return key
> ...
>>>> sorted(d.items(), key=sortkey)
> value: ('1', 'abc') sort-key: None
> value: ('3', 'pqr') sort-key: None
> value: ('2', 'xyz') sort-key: None
> [('1', 'abc'), ('3', 'pqr'), ('2', 'xyz')]
>

Thanks for that, Peter. That is a clever debugging technique I must use more 
often!

Not only do I now understand it, but I realise that Igor's original example 
worked by sheer coincidence -

$python -V
Python 2.7.3
$python -c "print({'1': None, '2': None, '3': None})"
{'1': None, '3': None, '2': None}
$python -c "print({'1': None, '2': None, '3': None})"
{'1': None, '3': None, '2': None}
$python -c "print({'1': None, '2': None, '3': None})"
{'1': None, '3': None, '2': None}

Keys of '1', '2', '3' are always stored in the sequence '1', 3', '2'.

$python3 -V
Python 3.3.2
$python3 -c "print({'1': None, '2': None, '3': None})"
{'2': None, '3': None, '1': None}
$python3 -c "print({'1': None, '2': None, '3': None})"
{'3': None, '2': None, '1': None}
$python3 -c "print({'1': None, '2': None, '3': None})"
{'1': None, '2': None, '3': None}

Due to the new 'hash randomisation' feature, the order is different every 
time.

In both versions, integer keys of 1, 2, 3 are always stored in the sequence 
1, 2, 3.

Frank






More information about the Python-list mailing list