logo

Python 辞書の get() メソッド

Python 辞書の get() メソッド 指定されたキーが辞書に存在する場合は、そのキーの値を返します。そうでない場合は、None を返します (get() が引数を 1 つだけ指定して使用された場合)。

Python 辞書 get() メソッドの構文:

構文: Dict.get(キー、デフォルト=なし)



パラメーター:

    key: 値を返したい項目のキー名。 Value: (オプション) キーが見つからない場合に返される値。デフォルト値は「なし」です。

戻り値: 指定されたキーまたはデフォルト値を持つ項目の値を返します。

Python 辞書 get() メソッドの例:

Python3








クイックソートJava

d>=> {>'coding'>:>'good'>,>'thinking'>:>'better'>}> print>(d.get(>'coding'>))>

inttostr java

>

>

出力:

good>

例 1: デフォルトのパラメーターを使用した Python get() メソッド。

パイソン




d>=> {>1>:>'001'>,>2>:>'010'>,>3>:>'011'>}> # since 4 is not in keys, it'll print 'Not found'> print>(d.get(>4>,>'Not found'>))>

>

>

出力:

CSVファイルをJavaから読み込む
Not found>

例 2: 連鎖した Python Dictionary get() メソッド

この特定のタスクを達成するために、値が存在しない場合は get() をチェックして割り当てます。キーが存在しない場合は、空の Python dict() を返します。

Python3




test_dict>=> {>'Gfg'> : {>'is'> :>'best'>}}> > # printing original dictionary> print>(>'The original dictionary is : '> +> str>(test_dict))> > # using nested get()> # Safe access nested dictionary key> res>=> test_dict.get(>'Gfg'>, {}).get(>'is'>)> > # printing result> print>(>'The nested safely accessed value is : '> +> str>(res))>

>

int を文字列 Java に変換します
>

出力:

The original dictionary is : {'Gfg': {'is': 'best'}} The nested safely accessed value is : best>

時間計算量: O(1) は、平均的な場合と最悪の場合の時間計算量が一定である辞書の get() メソッドを使用しているためです。
補助スペース: O(1) は、辞書と文字列値を格納するために一定量の追加メモリを使用するためです。