Help us understand the problem. What is going on with this article?

とっても便利なPythonの辞書型について覚え書き

More than 1 year has passed since last update.

はじめに

Pythonの辞書型はとっても便利なのですが、時折使い方をど忘れするので自分の備忘録のための書き残します。

辞書型?

keyとvalueが組み合わせになったデータの型です。
keyを使ってvalueを呼び出せるので、情報のヒモ付けと言う点でとっても便利。

辞書型の基本的な形
dic = {key1 : value1, key2 : value2}

使い方

新規の辞書作成

そのまま書き込む場合
dic = {"A" : 1, "B" : 2}
print(dic)
# 出力
# {"A" : 1, "B" : 2}
空の辞書に書き込んでいく場合
dic = {}
dic["key"] = "value"
print(dic)
# 出力
# {"key" : "value"}
valueにはリストも取れます
dic = {}
dic["key"] = ["value1", "value2"]
print(dic)
# 出力
# {"key" : ["value1", "value2"]}

要素を取り出す

既存の辞書のkeyに対応するvalueを取り出す
dic = {"A": "cat", "B": "dog"}
print(dic["B"])
# 出力
# "dog"
既存の辞書のkeyのリストを取り出す
dic = {"A": "cat", "B": "dog"}
print(dic.keys())
# 出力
# ["A", "B"]
既存の辞書のvalueのリストを取り出す
dic = {"A": "cat", "B": "dog"}
print(dic.values())
# 出力
# ["cat", "dog"]

要素を変更する

既存の辞書のvalueを変更
dic = {"A" : "cat"}
dic["A"] = "dog"
print(dic)
# 出力
# {"A": "dog"}
# keyに対してvalueの書き換えはできますが、その逆はできないので注意
既存の辞書の要素を削除する
dic = {"A": "cat", "B": "dog"}
dic.pop("A")
print(dic)
# 出力
# {"B": "dog"}

辞書に存在しないkeyを入れる

存在しないkeyを参照しようとすると
dic = {"A": "cat", "B": "dog"}
print(dic["C"])
# エラーが出る
# KeyError: 'C'
setdefault()を使うと
dic = {"A": "cat", "B": "dog"}
print(dic.setdefault("C", "hoge"))
# 出力
# "hoge"
# 第一引数に参照したいkeyを入れる
# keyがなかった場合、第二引数の値を返す

# setdefault()で追加された要素は、元の辞書に反映される
print(dic)
# 出力
# {'A': 'cat', 'C': 'hoge', 'B': 'dog'}
リストと組み合わせたりもできる
lst = ["A", "B", "C", "D", "E"]
dic = {}
n = 1
for i in lst:
    # nが奇数が偶数かでkeyを振り分ける
    # setdefault()の第二引数は空リスト=[]にしておく
    if n % 2 == 1:
        dic.setdefault(1, []).append(i)
    else:
        dic.setdefault(2, []).append(i)
    n = n + 1
print(dic)
# 出力
# {1: ['A', 'C', 'E'], 2: ['B', 'D']}
E_Schaf
非職業エンジニアのアラサー。pythonとGitLabの勉強中。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした