Write a Python program to add a key to a dictionary


The program creates a dictionary d with two key-value pairs "Name" and "Age". The first print statement prints the original dictionary. Then, the update method is used to add a new key-value pair "City" to the dictionary. The second print statement shows the updated dictionary with the new key-value pair.

Finally, a new key-value pair "Gender" is added to the dictionary using the square bracket notation. The third print statement displays the final version of the dictionary with three key-value pairs. In summary, the program demonstrates how to add new key-value pairs to a dictionary in Python, either by using the update method or by directly assigning values to a new key using square brackets.

Source Code

d = {"Name":"Ram" , "Age":23}
print(d)
d.update({"City":"Salem"})
print(d)
d["Gender"]="Male"
print(d)

Output

{'Name': 'Ram', 'Age': 23}
{'Name': 'Ram', 'Age': 23, 'City': 'Salem'}
{'Name': 'Ram', 'Age': 23, 'City': 'Salem', 'Gender': 'Male'}