[Tutor] Behavior of dictionary in mapping keys that evaluate equal
Steven D'Aprano
steve at pearwood.info
Wed May 11 21:19:21 EDT 2016
On Wed, May 11, 2016 at 02:00:47PM +0100, khalil zakaria Zemmoura wrote:
> Hi,
>
> Suppose we have a dict
> Dic = { True: 'yes', 1: 'No'}
>
> According to the Python 3 documentation, the keys must have a unique value
> so True is converted to integer because of the type coercion (boolean are
> subtype of integer) so boolean are winded to integer to be compared.
No, not quite. Keys aren't converted to anything. The above is
equivalent to:
Dic = {}
Dic[True] = 'yes'
Dic[1] = 'no'
That part is straight-forward. But remember that True == 1:
py> True == 1
True
and they have the same hash:
py> hash(True), hash(1)
(1, 1)
so as far as Python is concerned, they are the same key. The same
applies to the float 1.0:
py> d = {True: 'yes'}
py> d[1]
'yes'
py> d[1.0]
'yes'
One last fact to remember: if the key is already found in the dict, it
isn't replaced. So:
py> d = {1: 'no'}
py> d[True] = 'yes'
py> d
{1: 'yes'}
Does this now explain why
{True: 'yes', 1: 'no'}
returns {True: 'no'}?
--
Steve
More information about the Tutor
mailing list