Pythonの辞書(dict)のforループ処理(keys, values, items)

Modified: | Tags: Python, 辞書

Pythonの辞書オブジェクトdictの要素をfor文でループ処理するには辞書オブジェクトdictkeys(), values(), items()メソッドを使う。list()と組み合わせることで、辞書に含まれるすべてのキーや値のリストを取得することも可能。

Pythonにおけるforループの詳細は以下の記事を参照。

以下の辞書オブジェクトを例とする。

d = {'key1': 1, 'key2': 2, 'key3': 3}

なお、辞書オブジェクトをそのままfor文で回すとキーkeyが取得できる。list()ですべてのキーのリストに変換可能。

for k in d:
    print(k)
# key1
# key2
# key3

print(list(d))
# ['key1', 'key2', 'key3']

print(type(list(d)))
# <class 'list'>

keys(): 各要素のキーに対してforループ処理

上述のように、辞書オブジェクトをそのままfor文で回してもキーkeyが取得できるが、keys()メソッドを使ってもよい。

for k in d.keys():
    print(k)
# key1
# key2
# key3

keys()メソッドはdict_keysクラスを返す。list()でリスト化できる。

print(d.keys())
# dict_keys(['key1', 'key2', 'key3'])

print(type(d.keys()))
# <class 'dict_keys'>
print(list(d.keys()))
# ['key1', 'key2', 'key3']

print(type(list(d.keys())))
# <class 'list'>

dict_keysは集合演算をすることが可能。これを利用した例は以下の記事を参照。

values(): 各要素の値に対してforループ処理

各要素の値valueに対してforループ処理を行うには、values()メソッドを使う。

for v in d.values():
    print(v)
# 1
# 2
# 3

values()メソッドはdict_valuesクラスを返す。list()でリスト化できる。

print(d.values())
# dict_values([1, 2, 3])

print(type(d.values()))
# <class 'dict_values'>
print(list(d.values()))
# [1, 2, 3]

print(type(list(d.values())))
# <class 'list'>

valueは重複する場合があるため、dict_valuesの集合演算はサポートされていない。

items(): 各要素のキーと値に対してforループ処理

各要素のキーkeyと値valueの両方に対してforループ処理を行うには、items()メソッドを使う。

for k, v in d.items():
    print(k, v)
# key1 1
# key2 2
# key3 3

(key, value)のタプルとして受け取ることもできる。

for t in d.items():
    print(t)
    print(type(t))
    print(t[0])
    print(t[1])
    print('---')
# ('key1', 1)
# <class 'tuple'>
# key1
# 1
# ---
# ('key2', 2)
# <class 'tuple'>
# key2
# 2
# ---
# ('key3', 3)
# <class 'tuple'>
# key3
# 3
# ---

items()メソッドはdict_itemsクラスを返す。list()でリスト化できる。各要素が(key, value)のタプルとなる。

print(d.items())
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])

print(type(d.items()))
# <class 'dict_items'>
print(list(d.items()))
# [('key1', 1), ('key2', 2), ('key3', 3)]

print(type(list(d.items())))
# <class 'list'>

print(type(list(d.items())[0]))
# <class 'tuple'>

dict_itemsも集合演算をすることが可能。これを利用した例は以下の記事を参照。

関連カテゴリー

関連記事