Python : 辞書の基本操作編(get、dict 型、keys、values、items など)

TwitterFacebookHatena
  • 公開:2021-9-29
  • 更新:2023-10-26
  • 文章量:5319
  • Python

TL;DR

辞書はキーと値のセットを扱う。要素の順序は管理されておらず、0 や 1 などのオフセットは使わない。キーはイミュータブル(変更不可オブジェクト。数値型, bool, tuple, str, range, bytes, frozenset, file object)なら何でもよい。辞書はミュータブル(変更可能オブジェクト)なので、キーとバリュー要素を追加・修正・削除ができる。

辞書のポイント

  • 辞書はミュータブル(変更可能オブジェクト)
  • キー(key) と値(value) を対応づけるデータ
  • オフセットは使わない
  • 辞書を扱うデータ型として dict 型がある
  • 辞書のキーには、不変オブジェクト(文字列、数値、タプルなど)が利用可能
  • 辞書のキーには、可変オブジェクト(リスト、辞書など)は利用不可

辞書は、{} にキーと値を入れて作る。キーが辞書の中に存在しない場合、例外 KeyError が発生する。例外を発生させたくない場合は、後述する get()メソッドを使う。

fruits = {'apple': 1, 'banana': 2, 'grape': 3}
fruits['apple']

# 1

get()

get()メソッドを使うと、キーに対応する値を例外なしで返すことができる。

キーがあれば対応するバリューが返される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits.get('apple', '見つかりません')

# 'red'

キーが存在しなければ、オプションのバリューで設定した文字列が返される。設定しない場合は、None が返される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits.get('lemon', '見つかりません')

# '見つかりません'

dict 型

dict 型は辞書を扱う型である。辞書は {} を使う。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
type(fruits)

# dict

{} で囲まなくても、dict() に名前付き引数と値を渡すだけで辞書を作ることができる。

fruits = dict(apple=1, banana=2, grape=3)
fruits

# {'apple': 1, 'banana': 2, 'grape': 3}

dict() で変換する場合、リストの中にリストがあると、シーケンス(list, tuple, range)の先頭の要素がキー、第二要素は値になる。

foods = [['apple', 1], ['banana', 2], ['grape', 3]]
dict(foods)

# {'apple': 1, 'banana': 2, 'grape': 3}

タプルのリストも同じ結果となる。

foods = [('apple', 1), ('banana', 2), ('grape', 3)]
dict(foods)

# {'apple': 1, 'banana': 2, 'grape': 3}

keys()

keys()は辞書のすべてのキーを取得できる。リストにする場合は、list()関数を使う。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
list(fruits.keys())

# ['apple', 'banana', 'grape']

values()

values()は辞書のすべてのバリューを取得できる。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
list(fruits.values())

# ['red', 'yellow', 'purple']

items()

items() は辞書のすべてのキーとバリューを取得できる。結果は、タプルで返される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
list(fruits.items())

# [('apple', 'red'), ('banana', 'yellow'), ('grape', 'purple')]

len()

len()は、キーとバリューのペア数を数える。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
len(fruits)

# 3

辞書の結合

辞書の結合は {**変数, **変数} を使う。3 つ以上の辞書を渡すことができる。

fruits = {'apple':1, 'banana':2}
vegetable = {'broccoli': 3, 'carrot': 4}
{**fruits, **vegetable}

# {'apple': 1, 'banana': 2, 'broccoli': 3, 'carrot': 4}

update()の結合

update()関数を使うと、辞書のキーとバリューを結合できる。重複するキーがある場合、第二の辞書のバリューが渡される。

fruits = {'apple':1, 'banana':2}
vegetable = {'broccoli': 3, 'carrot': 4}
fruits.update(vegetable)
fruits

# {'apple': 1, 'banana': 2, 'broccoli': 3, 'carrot': 4}

fruits = {'apple':1, 'banana':2}
vegetable = {'apple': 3, 'carrot': 4}
fruits.update(vegetable)
fruits

# {'apple': 3, 'banana': 2, 'carrot': 4}

del()

del()文を使うと、指定したキーと、そのキーに対応するバリューを削除する。対応するキーが存在しない場合は、例外を返す。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
del fruits['banana']

fruits

# {'apple': 'red', 'grape': 'purple'}

pop()

dict.pop() も指定したキーに対応するバリューを削除する。対応するキーが存在しない場合は、例外を返すが、第二引数にデフォルトバリューを設定すると例外は発生せず、辞書は変更されない。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits.pop('banana')

fruits

# {'apple': 'red', 'grape': 'purple'}

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits.pop('lemon', '見つかりませんでした')

fruits

# {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}

clear()

clear() を使うと、辞書の中にあるキーとバリューを全て削除できる。空の辞書を代入しても同じように全て削除される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits.clear()
fruits

# {}

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
fruits = {}
fruits

# {}

copy() と deepcopy()

元の辞書に影響を与えず変更を加えたいときは、copy()を使う。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
foods = fruits.copy()
foods['lemon'] = 'yellow'
foods

# {'apple': 'red', 'banana': 'yellow',
#'grape': 'purple', 'lemon': 'yellow'}

fruits

# {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}

要素の中に二次元配列が存在する場合、元の辞書のリストを書き換えると、コピー先も書き換えられてしまうが、

fruits = {'apple':['red', 'green'], 'banana':'yellow', 'grape':'purple'}
fruits_copy = fruits.copy()
fruits['apple'][1] = 'yellow'
fruits_copy

# {'apple': ['red', 'yellow'], 'banana': 'yellow', 'grape': 'purple'}

copy モジュールをインポートして、copy.deepcopy() を使うと、コピー先は変更されない。

import copy
fruits = {'apple':['red', 'green'], 'banana':'yellow', 'grape':'purple'}
fruits_copy = copy.deepcopy(fruits)
fruits['apple'][1] = 'yellow'
fruits_copy

# {'apple': ['red', 'green'], 'banana': 'yellow', 'grape': 'purple'}

for

for 文を使うと、キーが返される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
for i in fruits:
    print(i)

# apple
# banana
# grape

values() 関数を使うとバリューを返す。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
for i in fruits.values():
    print(i)
# red
# yellow
# purple

dict.items()関数を使うとキーとバリューがタプルで返される。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
for i in fruits.items():
    print(i)
# ('apple', 'red')
# ('banana', 'yellow')
# ('grape', 'purple')

dict.items()の戻り値を、そのまま表示するか文字列に代入したい場合は、for の引数を 2 つ設定するとよい。

fruits = {'apple':'red', 'banana':'yellow', 'grape':'purple'}
for a, b in fruits.items():
    print(f'{a}{b} です。')

# apple は red です。
# banana は yellow です。
# grape は purple です。

真理値

空の辞書は偽となるが、要素が一つ以上存在する場合は真となる。

bool({})

# False

bool({'a': 0})

# True

in 演算子を使うと、要素の有無を判定する。

words = {'a': 1, 'b':2, 'c':3}
'a' in words

# True

値に対して in 演算子を使う場合は、values()を付ける。

words = {'a': 1, 'b':2, 'c':3}
1 in words.values()

# True

Python : 辞書の基本操作編(get、dict 型、keys、values、items など)