1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonのイテレータのkeyとvalueどっちも使いたい

Posted at

for 文の中で dict をイテレータとして使う時 key と value 両方使いたい時ってありますよねー。あと list をいてラータにする場合の index も。

毎回結局どう書けばいいんだっけってなるのでメモに残す。

ちなみに今まではこうしてた↓

python3
>>> dict = {'a': 10, 'b': 20, 'c': 30}
>>> for key in dict.keys():
>>>    print('key: ', key, ' ,value: ', dict[key])
key:  a  ,value:  10
key:  b  ,value:  20
key:  c  ,value:  30

for の後ろの変数を二つにして dict.items() を渡せばそれぞれに key, value が入るらしい

python3
>>> dict = {'a': 10, 'b': 20, 'c': 30}
>>> for key, value in dict.items():
>>>    print('key: ', key, ' ,value: ', value)
key:  a  ,value:  10
key:  b  ,value:  20
key:  c  ,value:  30

list で index と value を使いたい場合は enumerate(list) を使用する

python3
>>> l = ['a', 'b', 'c']
>>> for index, value in enumerate(l):
>>>    print('index: ', index, ' ,value: ', value)
index:  0  ,value:  a
index:  1  ,value:  b
index:  2  ,value:  c

pandas の Series や DataFrame でも同じようにできますが、index にセットした値は適用されず index=0,1,2,... となります

ちなみに js の Map では同じようなことを分割代入的に書きますよね

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?