1
1

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 2024-06-12

辞書型は、キーと値のペアを含む組み込みのデータ型です。辞書はキーによってユニークに値にアクセスできるため、連想配列や、ハッシュとも呼ばれます。

辞書の作成

# 空の辞書
empty_dict = {}

# 値を含む辞書
person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}

キーは整数やストリングなどのイミュータブル(変更不可能)なオブジェクトを使用します。値には任意のオブジェクトを設定できます。

要素へのアクセスと変更

person = {'name': 'Alice', 'age': 25}

# 値へのアクセス
print(person['name'])  # 出力: Alice

# 値の変更
person['age'] = 26

# 新しいキーと値の追加
person['city'] = 'Tokyo'

辞書のメソッド

person = {'name': 'Alice', 'age': 25}

# キーの存在確認
print('name' in person)  # 出力: True

# 値の取得(キーが存在しない場合はデフォルト値)
print(person.get('city', 'Unknown'))  # 出力: Unknown

# キーと値のペアを追加(update)
person.update({'city': 'Tokyo', 'job': 'Engineer'})

# キーと値のペアをリストで取得
print(person.items())  # 出力: dict_items([('name', 'Alice'), ('age', 25), ('city', 'Tokyo'), ('job', 'Engineer')])

# キーのみをリストで取得 
print(person.keys())  # 出力: dict_keys(['name', 'age', 'city', 'job'])

# 値のみをリストで取得
print(person.values())  # 出力: dict_values(['Alice', 25, 'Tokyo', 'Engineer'])

辞書の反復処理

person = {'name': 'Alice', 'age': 25, 'city': 'Tokyo'}

# キーを反復
for key in person:
    print(key, person[key])

# キーと値のペアを反復
for key, value in person.items():
    print(key, value)
name Alice
age 25
city Tokyo

name Alice
age 25
city Tokyo

辞書型は、キーと値の関連付けが容易にでき、検索や更新が高速に行えるので、データの格納や管理に適しています。ただし、順序は保証されないことに注意が必要です。辞書内包表記を使えば、より簡潔に辞書を作成できます。

参考) 東京工業大学情報理工学院 Python早見表

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?