0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

python 辞書におけるリストとタプル

Last updated at Posted at 2025-01-16

dict0 = {('key0', 'key1'): 'value0'}
dict1 = {['key0', 'key1']: 'value0'}
dict2 = {'key': ('value1', 'value2')}
dict3 = {'key': ['value1', 'value2']}

説明

辞書のkeyにできるのはタプル〇、リスト×
辞書のvalueにできるのはタプル〇、リスト〇

そもそもタプルとリストの違いって…

  • タプルはハッシュ可能、変更不可能
  • リストはハッシュ不可能、変更可能

であるため、ハッシュ不可能なものはkeyに入れられない。
ただし、タプルであっても、ハッシュ不可能な要素を含んでいる場合にはハッシュ不可能なのでkeyにできない。

dict0 = {('key0', ['key1']): 'value0'}  # エラー

※なお、厳密にはハッシュ可能性と変更可能性は、同じではない。
例えば、 ユーザー定義のクラスのインスタンスは変更可能だけど、ハッシュ可能なのでkeyにできる。

0
0
4

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?