"Peter Otten" <[email protected]> wrote in message
news:[email protected]...
> 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
--
https://mail.python.org/mailman/listinfo/python-list