Pythonのディクショナリからループでキー値と値を取得する方法

Pythonのディクショナリからループでキー値と値を取得するサンプルコードを以下に記します。
(Pythonのディクショナリは、他の言語ではハッシュは連想配列と言われるものです。)

htmlinsert(): The given local file does not exist or is not readable.

動作確認環境

関連記事

サンプルコード

以下のサンプルコードは、ディクショナリのキーのみ、キーと値のペア、値のみの3種類が動作します。
指定なし、iteritems()、itervalues()により動作が異なってきます。

d = {"1st":"sakura", "2nd":"suzuran", "3rd":"tsubaki"}

# print key value
for key in d:
    print key

#print key and value
for key, val in d.iteritems():
    print key + " : " + val

#print value
for val in d.itervalues():
    print val

実際に上記スクリプトを実行した時の出力です。

2nd
3rd
1st
2nd : suzuran
3rd : tsubaki
1st : sakura
suzuran
tsubaki
sakura

以上、Pythonのディクショナリからキー値および値を取得する方法でした。


トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2025-03-12 (水) 11:46:15