How to add key value pairs to a dictionary in Python

Syntax:

myDict.update( { "key1": 1, "key2": 2 }  )

New key values pairs are added to a dictionary using the update method and passing a dictionary containing the values to update.

Example:

This example creates a dictonary with 2 key value pairs. Two new values are added using the update method. The key named "key3" has the value 3 set instead of the initial value. The same way the key "key5" is added along with the value 5. The content of the dictionary is then written in the output.

# Create the dictionary
myDict = { "key1": 1, "key2": 2 }
	
# Add a new key value pair
myDict.update( { "key3": 1, "key4": 4 }  )

# Update a value
myDict["key3"] = 3

# Add a new key value pair
myDict["key5"] = 5

# Print the content of the dictionary
for k in myDict.keys():
    print( k + " = " + str( myDict[ k ] ) )

The output will be:

key1 = 1
key2 = 2
key3 = 3
key4 = 4
key5 = 5

References:

Python

Recent Comments