辞書を定義する
Pythonにおける辞書(dict)はRubyでのハッシュやJavaでのHashMapのようなもので、キーと値のペアを持ちます。
>>> d = dict({"SPAM":120, "Egg":80, "Bacon":150})
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
キーに関連付けられた値を取得する
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d["Egg"]
80
>>> d["SPAM"]
120
>>> d.get("Bacon")
150
辞書に要素を追加する
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d["Sausage"] = 140
>>> print(d)
{'Bacon': 150, 'Sausage': 140, 'Egg': 80, 'SPAM': 120}
辞書内にキーが存在するかどうか調べる
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d
{'Bacon': 150, 'Egg': 80, 'SPAM': 120}
>>> "SPAM" in d
True
辞書の要素数を取得する
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> len(d)
3
辞書から値を取り出す
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d.pop("SPAM")
120
>>> print(d)
{'Bacon': 150, 'Egg': 80}
辞書からキーと値のペアを取り出す
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d.popitem()
('Bacon', 150)
辞書を空にする
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> d.clear()
>>> print(d)
{}
辞書からエントリを削除する
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> del d["SPAM"]
>>> print(d)
{'Bacon': 150, 'Egg': 80}
辞書の全エントリに対して処理を行う
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> for k, v in d.items():
... print(k,v)
...
Bacon 150
Egg 80
SPAM 120
辞書をリストに変換する
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> list(d.keys())
['Bacon', 'Egg', 'SPAM']
>>> list(d.values())
[150, 80, 120]
>>> list(d.items())
[('Bacon', 150), ('Egg', 80), ('SPAM', 120)]
辞書の要素をランダムに抽出する
>>> import random
>>> d = dict(Egg=80, Bacon=150, SPAM=120)
>>> random.choice(list(d.keys()))
'Egg'
>>> random.choice(list(d.values()))
80
>>> random.choice(list(d.items()))
('Egg', 80)
最終更新:2009年08月08日 17:21