logo

Pythonでキーと値のペアを辞書に追加する

辞書 Python では、データ値の順序付けされていないコレクションであり、マップのようなデータ値を格納するために使用されます。要素として単一の値のみを保持する他のデータ型とは異なり、Dictionary はキー:値のペアを保持します。 Dictionary を使用しているときに、場合によっては、辞書内のキー/値を追加または変更する必要があります。 Python でキーと値のペアを辞書に追加する方法を見てみましょう。

コード #1: 添え字表記の使用 このメソッドは、キーに値を割り当てることによって、ディクショナリに新しいキー:値のペアを作成します。

Python3






# Python program to add a key:value pair to dictionary> dict> => {>'key1'>:>'geeks'>,>'key2'>:>'for'>}> print>('Current>Dict> is>: ',>dict>)> > # using the subscript notation> # Dictionary_Name[New_Key_Name] = New_Key_Value> dict>[>'key3'>]>=> 'Geeks'> dict>[>'key4'>]>=> 'is'> dict>[>'key5'>]>=> 'portal'> dict>[>'key6'>]>=> 'Computer'> print>('Updated>Dict> is>: ',>dict>)>

>

スキャナー.ネクストJava
>

出力:

現在の辞書は: {'key2': 'for', 'key1': 'geeks'} 更新された辞書は: {'key3': 'Geeks', 'key5': 'portal', 'key6': 'Computer', 'key4': 'is', 'key1': 'オタク', 'key2': 'for'}

時間計算量: ○(1)
補助スペース: ○(1)

コード #2: update() メソッドの使用

Python3




dict> => {>'key1'>:>'geeks'>,>'key2'>:>'for'>}> print>('Current>Dict> is>: ',>dict>)> # adding dict1 (key3, key4 and key5) to dict> dict1>=> {>'key3'>:>'geeks'>,>'key4'>:>'is'>,>'key5'>:>'fabulous'>}> dict>.update(dict1)> # by assigning> dict>.update(newkey1>=>'portal'>)> print>(>dict>)>

>

>

出力:

現在の辞書は次のとおりです: {'key2': 'for', 'key1': 'geeks'} {'newkey1': 'portal', 'key4': 'is', 'key2': 'for', 'key1': 'オタク', 'key5': '素晴らしい', 'key3': 'オタク'}

時間計算量: ○(1)
補助スペース: ○(1)

コード #3: Key:valueを入力として受け取る

Python3


カイリー・ジェンナー兄弟



# Let's add key:value to a dictionary, the functional way> # Create your dictionary class> class> my_dictionary(>dict>):> ># __init__ function> >def> __init__(>self>):> >self> => dict>()> > ># Function to add key:value> >def> add(>self>, key, value):> >self>[key]>=> value> # Main Function> dict_obj>=> my_dictionary()> # Taking input key = 1, value = Geek> dict_obj.key>=> input>('Enter the key: ')> dict_obj.value>=> input>('Enter the value: ')> dict_obj.add(dict_obj.key, dict_obj.value)> dict_obj.add(>2>,>'forGeeks'>)> print>(dict_obj)>

>

>

出力:

 {'1': 'Geeks', 2: 'forGeeks'}>

時間計算量: ○(1)
補助スペース: の上)

コード #4: 辞書内包を使用する

たとえば、次のように既存の辞書にキーと値のペアを追加する新しい辞書を作成できます。

Python3




existing_dict>=> {>'key1'>:>'value1'>,>'key2'>:>'value2'>}> new_key>=> 'key3'> new_value>=> 'value3'> updated_dict>=> {>*>*>existing_dict, new_key: new_value}> print>(updated_dict)> #This code is contributed by Edula Vinay Kumar Reddy>

>

>

出力

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}>

これにより、updated_dict という新しい辞書が作成されます。この辞書には、existing_dict のすべてのキー:値のペアと、新しいキー:値のペア「key3」:「value3」が含まれます。

時間計算量: の上)
補助スペース: の上)