Python 辞書の理解

List Comprehension と同様に、Python では辞書内包表記が可能です。簡単な式を使用して辞書を作成できます。辞書の理解は次のような形式になります。 {key: 反復可能な (key, value) の値}

Python 辞書の理解の例

ここには 2 つあります リスト 名前付きのキーと値を使用して、それらを反復処理しています。 ジップ() 関数。

パイソン




# Python code to demonstrate dictionary> # comprehension> # Lists to represent keys and values> keys> => [> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> ]> values> => [> 1> ,> 2> ,> 3> ,> 4> ,> 5> ]> # but this line shows dict comprehension here> myDict> => { k:v> for> (k,v)> in> zip> (keys, values)}> # We can use below too> # myDict = dict(zip(keys, values))> print> (myDict)>

出力:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} 

fromkeys() メソッドの使用

ここでは、特定のキーと値を含む辞書を返す fromkeys() メソッドを使用しています。

Python3




dic> => dict> .fromkeys(> range> (> 5> ),> True> )> print> (dic)>

出力:

{0: True, 1: True, 2: True, 3: True, 4: True} 

辞書内包を使用して辞書を作成する

例 1:

パイソン




# Python code to demonstrate dictionary> # creation using list comprehension> myDict> => {x: x> *> *> 2> for> x> in> [> 1> ,> 2> ,> 3> ,> 4> ,> 5> ]}> print> (myDict)>

出力:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 

例 2:

パイソン




sDict> => {x.upper(): x> *> 3> for> x> in> 'coding '> }> print> (sDict)>

出力:

{'O': 'ooo', 'N': 'nnn', 'I': 'iii', 'C': 'ccc', 'D': 'ddd', 'G': 'ggg'} 

辞書理解における条件文の使用

例 1:

if ステートメントや else ステートメント、その他の式でも辞書の内包表記を使用できます。以下の例では、数値を 4 で割り切れない立方体にマッピングします。

パイソン




# Python code to demonstrate dictionary> # comprehension using if.> newdict> => {x: x> *> *> 3> for> x> in> range> (> 10> )> if> x> *> *> 3> %> 4> => => 0> }> print> (newdict)>

出力:

{0: 0, 8: 512, 2: 8, 4: 64, 6: 216} 

ネストされた辞書内包表記の使用

ここではネストされた 辞書 辞書読解の助けを借りて。

Python3




# given string> l> => 'GFG'> # using dictionary comprehension> dic> => {> > x: {y: x> +> y> for> y> in> l}> for> x> in> l> }> print> (dic)>

出力:

{'G': {'G': 'GG', 'F': 'GF'}, 'F': {'G': 'FG', 'F': 'FF'}}