今回は、Pythonの辞書を更新する手順を公開します。
Python辞書を更新するステップを開始する
Python辞書は、キーと値のペアでデータ要素を保持するデータ構造であり、基本的に要素の順序付けされていないコレクションとして機能します。
関連付けられたキーの値を更新するために、Python Dictには dict.update() メソッド が組み込まれており、Python Dictionaryを更新することができます。
dict.update() メソッドは、入力辞書のキーに関連付けられた値を更新するために使用されます。
構文は以下の通りです。
input_dict.update(dict)
|
この関数は値を返さず、同じ入力辞書を新しく関連付けられたキーの値で更新します。
例えば、以下の様になります。
dict = {"Python":100,"Java":150}
up_dict = {"Python":500}
print("Dictionary before updation:",dict)
dict.update(up_dict)
print("Dictionary after updation:",dict)
|
結果は、以下の通りになります。
Dictionary before updation: {'Python': 100, 'Java': 150}
Dictionary after updation: {'Python': 500, 'Java': 150}
|
イテラブルでPythonの辞書を更新する
辞書のキー値の更新とは別に、Python辞書に他のイテラブルからの値を追加して更新することもできます。
構文は以下の通りです。
dict.update(iterable)
|
例えば、以下の様になります。
dict = {"Python":100,"Java":150}
print("Dictionary before updation:",dict)
dict.update(C = 35,Fortran = 40)
print("Dictionary after updation:",dict)
|
上記の例では、update()関数に渡された値で入力dictを更新しています。
このように、入力dictは関数に渡された値で追記され、更新されます。
結果は以下の通りです。
Dictionary before updation: {'Python': 100, 'Java': 150}
Dictionary after updation: {'Python': 100, 'Java': 150, 'C': 35, 'Fortran': 40}
|
ネストしたPython辞書を更新する
ネストされた辞書は、辞書の中の辞書です。
Pythonのネストされた辞書は、以下の構文でそれぞれのキーの値を更新することができます。
構文は以下の様な感じです。
構文:
dict[outer-key][inner-key]='new-value'
|
例えば、以下の様になります。
dict = { 'stud1_info':{'name':'Safa','Roll-num':25},'stud2_info':{'name':'Ayush','Roll-num':24}}
print("Dictionary before updation:",dict)
dict['stud2_info']['Roll-num']=78
dict['stud1_info']['name']='Riya'
print("Dictionary after updation:",dict)
|
上記の例では、inner key:’Roll-num’ of the outer key:’stud2_info’ を78に、inner key:’name’ of the outer key:’stud1_info’ を ‘Riya’ に更新している。
結果を出力すると、以下の様になります。
Dictionary before updation: {'stud1_info': {'name': 'Safa', 'Roll-num': 25}, 'stud2_info': {'name': 'Ayush', 'Roll-num': 24}}
Dictionary after updation: {'stud1_info': {'name': 'Riya', 'Roll-num': 25}, 'stud2_info': {'name': 'Ayush', 'Roll-num': 78}}
|
まとめ
この記事では、Python辞書とネストされた辞書の値を更新する方法について理解しました。
辞書の概念について深く理解するために、Python辞書チュートリアルに目を通すことを強くお勧めします。
参考文献
- Python辞書 – JournalDev