13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

辞書(dict)のキーに 0, 1, False, True を使った場合の興味深い挙動

13
Last updated at Posted at 2020-02-02

Pythonの辞書(dict)キーにはHashableなオブジェクトが使え、hash値をキーに使用します。
Pythonのbool型はint型のサブクラスとして実装されており、False0 と、True1 と同じhash値になっています。

>>> hash(0)
0
>>> hash(False)
0
>>> hash(1)
1
>>> hash(True)
1

では、0, 1, False, True を辞書キーとして使うとどうなるかを見てみます。

>>> d = { 0: 'zero', True: 'true' }
>>> d
{0: 'zero', True: 'true'}
>>> d[0]
'zero'
>>> d[True]
'true'
>>> d[False]
'zero'
>>> d[1]
'true'

辞書にない False1 も取得できてしまいました。
ハッシュ値が同じなので、当然といえば当然な挙動です。

辞書に代入してみます。

>>> d
{0: 'zero', True: 'true'}
>>> d[False] = 'false'
>>> d[1] = 'one'
>>> d
{0: 'false', True: 'one'}

キーは 0True のまま、値が 'false''one' に更新されました。

キーは最初に代入したときの値が使われ、値は最後に代入した値になることがわかりました。
当然と言えば当然ですが、興味深い結果でした。

>>> d = { 0: '', True: '', 1: '', False: ''}
>>> d
{0: '', True: ''}

追記:

公式ドキュメントに書いてありました。

比較した際に等しいとみなされる値 (例えば 1 と 1.0 と True) は、どれを使っても同じエントリーに関連付けられます。

13
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?