イテレータのkeyとvalue両方使いたい

超初心者向けです。やりたいことはタイトルの通り。今まではこうしてた↓

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 で似たようなこと(key ではなく index)をしたい場合は 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 では同じようなことを分割代入的に書きますよね