Latest web development tutorials

Pythonの辞書(辞書)fromkeys()メソッド

説明

Pythonの辞書(辞書)fromkeys()関数は、シーケンスseqの要素に新しい辞書を作成するために使用される初期値に対応するすべてのキーの辞書として辞書のキー、値を行います。

文法

fromkeys()メソッドの構文:

dict.fromkeys(seq[, value]))

パラメータ

  • SEQ - 辞書のキーのリスト。
  • 値 - キーシーケンス(配列)の値を設定するオプションのパラメータ。

戻り値

このメソッドは、リストを返します。

次の例では、使用するfromkeys()関数を示しています。

#!/usr/bin/python

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print "New Dictionary : %s" %  str(dict)

dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" %  str(dict)

上の例の出力は、次のとおりです。

New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}