Python 辞書の update() メソッド 別のディクショナリ オブジェクトまたはキーと値のペアの反復可能な要素からディクショナリを更新します。
例:
Original dictionary : {'A': 'Geeks', 'B': 'For'} Updated dictionary : {'A': 'Geeks', 'B': 'Geeks'} Original dictionary : {'A': 'Geeks', 'B': 'For'} Updated dictionary : {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}> Python辞書更新メソッドの構文
の辞書 update() メソッド パイソン 次の構文があります。
構文: dict.update([その他])
パラメーター: このメソッドは、辞書またはキーと値のペア (通常はタプル) の反復可能なオブジェクトをパラメータとして受け取ります。
戻り値: これは値を返しませんが、ディクショナリ オブジェクトまたはキーと値のペアの反復可能なオブジェクトの要素でディクショナリを更新します。
Python 辞書 update() の例
のデータを更新する update() メソッドの例をいくつか見てみましょう。 Python辞書 。
別の辞書で更新する
ここでは、update() メソッドを使用して Python で辞書を更新し、別の辞書をパラメータとして渡しています。 2 番目の辞書は更新された値に使用されます。
Python3
FCF
# Python program to show working> # of update() method in Dictionary> # Dictionary with three items> Dictionary1>=> {>'A'>:>'Geeks'>,>'B'>:>'For'>, }> Dictionary2>=> {>'B'>:>'Geeks'>}> # Dictionary before Updation> print>(>'Original Dictionary:'>)> print>(Dictionary1)> # update the value of key 'B'> Dictionary1.update(Dictionary2)> print>(>'Dictionary after updation:'>)> print>(Dictionary1)> |
米国の州
>
>
出力:
Original Dictionary: {'A': 'Geeks', 'B': 'For'} Dictionary after updation: {'A': 'Geeks', 'B': 'Geeks'}> Iterable で更新する
この例では、別の辞書を使用する代わりに、反復可能な値を update() 関数に渡しました。
Python3
# Python program to show working> # of update() method in Dictionary> # Dictionary with single item> Dictionary1>=> {>'A'>:>'Geeks'>}> # Dictionary before Updation> print>(>'Original Dictionary:'>)> print>(Dictionary1)> # update the Dictionary with iterable> Dictionary1.update(B>=>'For'>, C>=>'Geeks'>)> print>(>'Dictionary after updation:'>)> print>(Dictionary1)> |
>
>出力
Original Dictionary: {'A': 'Geeks'} Dictionary after updation: {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}> キーが存在する場合の Python 辞書の値の更新
この例では、特定のキーが存在する場合に Python で辞書の値を更新します。キーが辞書に存在しない場合は、単にキーが存在しないことを出力します。
Python3
文字列で比較する
def> checkKey(>dict>, key):> > >if> key>in> dict>.keys():> >print>(>'Key exist, '>, end>=>' '>)> >dict>.update({>'m'>:>600>})> >print>(>'value updated ='>,>600>)> >else>:> >print>(>'Not Exist'>)> dict> => {>'m'>:>700>,>'n'>:>100>,>'t'>:>500>}> > key>=> 'm'> checkKey(>dict>, key)> print>(>dict>)> |
>
>
出力:
Key exist, value updated = 600 {'m': 600, 'n': 100, 't': 500}> キーが存在しない場合の Python 辞書の値の更新
ここでは、辞書にキーが存在しない辞書の値を更新してみます。この場合、キーと値は新しい要素としてディクショナリに追加されます。
リンクリストと配列リスト
Python3
def> checkKey(>dict>, key):> > >if> key>not> in> dict>.keys():> >print>(>'Key doesn't exist So, a new Key-Value pair will be created'>)> >dict>.update({key:>600>})> >else>:> >print>(>'Key Exist'>)> dict> => {>'m'>:>700>,>'n'>:>100>,>'t'>:>500>}> > key>=> 'k'> checkKey(>dict>, key)> print>(>dict>)> |
>
>
出力:
Key doesn't exist So, a new Key-Value pair will be created {'m': 700, 'n': 100, 't': 500, 'k': 600}>