Pythonの辞書(dict)のforループ処理(keys, values, items)
Pythonの辞書オブジェクトdict
の要素をfor文でループ処理するには辞書オブジェクトdict
のメソッドkeys()
, values()
, items()
を使う。list()
と組み合わせることで、辞書に含まれるすべてのキーや値のリストを取得することも可能。
keys()
: 各要素のキーkey
に対してforループ処理values()
: 各要素の値value
に対してforループ処理items()
: 各要素のキーkey
と値value
に対してforループ処理
以下の辞書オブジェクトを例とする。
d = {'key1': 1, 'key2': 2, 'key3': 3}
source: dict_keys_values_items.py
なお、辞書オブジェクトをそのままfor文で回すとキーkey
が取得できる。
for k in d:
print(k)
# key1
# key2
# key3
source: dict_keys_values_items.py
スポンサーリンク
keys(): 各要素のキーに対してforループ処理
上述のように、辞書オブジェクトをそのままfor文で回してもキーkey
が取得できるが、keys()
メソッドを使ってもよい。
for k in d.keys():
print(k)
# key1
# key2
# key3
source: dict_keys_values_items.py
keys()
メソッドはdict_keys
クラスを返す。リストにしたい場合は、list()
関数でリスト化できる。
keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>
k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key2', 'key3']
# <class 'list'>
source: dict_keys_values_items.py
dict_keys
は集合演算をすることが可能。これを利用した例は以下の記事を参照。
values(): 各要素の値に対してforループ処理
各要素の値value
に対してforループ処理を行いたい場合は、values()
メソッドを使う。
for v in d.values():
print(v)
# 1
# 2
# 3
source: dict_keys_values_items.py
values()
メソッドはdict_values
クラスを返す。リストにしたい場合は、list()
関数でリスト化できる。
values = d.values()
print(values)
print(type(values))
# dict_values([1, 2, 3])
# <class 'dict_values'>
v_list = list(d.values())
print(v_list)
print(type(v_list))
# [1, 2, 3]
# <class 'list'>
source: dict_keys_values_items.py
value
は重複する場合があるため、dict_values
の集合演算はサポートされていない。
items(): 各要素のキーと値に対してforループ処理
各要素のキーkey
と値value
の両方に対してforループ処理を行いたい場合は、items()
メソッドを使う。
for k, v in d.items():
print(k, v)
# key1 1
# key2 2
# key3 3
source: dict_keys_values_items.py
(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
# ---
source: dict_keys_values_items.py
items()
メソッドはdict_items
クラスを返す。リストにしたい場合は、list()
関数でリスト化できる。各要素が(key, value)
のタプルとなる。
items = d.items()
print(items)
print(type(items))
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
# <class 'dict_items'>
i_list = list(d.items())
print(i_list)
print(type(i_list))
# [('key1', 1), ('key2', 2), ('key3', 3)]
# <class 'list'>
print(i_list[0])
print(type(i_list[0]))
# ('key1', 1)
# <class 'tuple'>
source: dict_keys_values_items.py
dict_items
も集合演算をすることが可能。これを利用した例は以下の記事を参照。
スポンサーリンク