[Tutor] Behavior of dictionary in mapping keys that evaluate equal

cs at zip.com.au cs at zip.com.au
Wed May 11 18:42:45 EDT 2016


On 11May2016 14:00, khalil zakaria Zemmoura <zemmoura.khalil at gmail.com> wrote:
>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.

As it happens. The core lesson here is that usually you want all your 
dictionary keys to be the same type.

>If that's what happen, why when running Dic.items() it return [(True,
>'No')] instead of [(1, 'No')]

Because the dictionary is assembled sequentially (probably an implementation 
detail, though since Python expressions are evaluated left to right it might 
possibly be guarrenteed).

So:

  First 'yes' is loaded into the dict with the key True.

  The 'No' is loaded, using key 1. This finds the same slot as True, and puts 
  'No' there. Without changing the key value. So true now has 'No' stored with 
  it.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list