Python 辞書と集合(SET)

辞書

  • キーと値の組み合わせでデータ管理する構造
  • 値を取り出すために使用する文字列などの値をキーと呼ぶ
  • キーを使って 高速に検索・更新できる
  • キーは重複不可(一意)
  • キーは変更不可(immutable)型のみ
    • 数値、文字列、タプルはキーにできる
    • リスト(list) 、辞書(dict)、セット(set)はキーにできない
  • 順序保持(Python 3.7以降)
構文

変数名={“キー”:値,”キー”:値,・・・}

# 辞書を定義
cake ={"ID":1,"Name":"カップケーキ","Price":250}
print(cake["Price"])

# Priceを300に変更
cake["Price"]=300
print(cake["Price"])

print(cake)
print(cake.keys())
print(cake.values())

実行結果:
250
300
{‘ID’: 1, ‘Name’: ‘カップケーキ’, ‘Price’: 300}
dict_keys([‘ID’, ‘Name’, ‘Price’])
dict_values([1, ‘カップケーキ’, 300])

主要メソッド

メソッド説明
.keys()キー一覧dict.keys()
.values()値一覧dict.values()
.items()(キー, 値)のタプル一覧dict.items()
.get(key, 初期値)キーが無い時のエラー防止d.get("age", 0)
.pop(key)指定キー削除d.pop("name")
.update({...})一括更新d.update(x)
.setdefault(key, 値)キーと値の追加d.setdefault(“年齢”, 20)

getメソッド

  • 辞書の値を取得
  • キーが存在しない場合は、「None」となり、エラーは発生しない
cake ={"ID":1,"Name":"カップケーキ","Price":250}
print(cake.get("Name"))
print(cake.get("name"))

実行結果:
カップケーキ
None

setdefaultメソッド

profile={"ID":1,"名前":"田中太郎"}
print(profile)

profile.setdefault("age",20)
print(profile)

実行結果:
{‘ID’: 1, ‘名前’: ‘田中太郎’}
{‘ID’: 1, ‘名前’: ‘田中太郎’, ‘age’: 20}

updateメソッド

profile={"ID":1,"名前":"田中太郎"}
print(profile)

new_profile={"名前":"山田太郎","年齢":20}
profile.update(new_profile)
print(profile)

print(profile.get("名前"))

実行結果:
{‘ID’: 1, ‘名前’: ‘田中太郎’}
{‘ID’: 1, ‘名前’: ‘山田太郎’, ‘年齢’: 20}
山田太郎

popメソッド

profile={"ID":1,"名前":"田中太郎","年齢":20}
print(profile)

profile.pop("名前")
print(profile)

実行結果:
{‘ID’: 1, ‘名前’: ‘田中太郎’, ‘年齢’: 20}
{‘ID’: 1, ‘年齢’: 20}

clear メソッド

profile={"ID":1,"名前":"田中太郎","年齢":20}
print(profile)

# profile.pop("名前")
profile.clear()
print(profile)

実行結果:
{‘ID’: 1, ‘名前’: ‘田中太郎’, ‘年齢’: 20}
{}

len関数

cake ={"ID":1,"Name":"カップケーキ","Price":250}
print(len(cake))

実行結果:
3

集合(SET)

  • 重複を許さない 同じ値は1つにまとまる
  • 順序なし 並びは保証されない
  • 集合演算ができる 和・積・差などが簡単
  • 集合で、インデックス指定はできない
構文

集合名={値,値,値,・・・}

addメソッド(追加)

number_Set={10,20,30}
print(number_Set)

number_Set.add(40)
print(number_Set)

number_Set.add(20)
print(number_Set)

実行結果:
{10, 20, 30}
{40, 10, 20, 30}
{40, 10, 20, 30}

コメント