In this Python program, we will learn how to add key-value pairs to a dictionary. In this program, we are adding key-value pairs to a dictionary in two ways: the first way is to use the python dictionary built-in update()
function to update the element in the dictionary and the second way is without using any python dictionary built-in function.
Here is the source code of the program to add key-value pairs to a dictionary in python.
In this program, we used the python dictionary built-in update()
function to update the set, adding from the other iterable to the dictionary.
# Python Program to Add Key-Value Pair to a Dictionary Using update() function
# Take the Input from the user
key = input("Enter the Key: ")
value = input("Enter the Value: ")
myDict = {}
# Add Key-Value Pair to a Dictionary in Python
myDict.update({key:value})
print("\nUpdated Dictionary = ", myDict)
Enter the Key: Website
Enter the Value: Tutorialsrack.com
Updated Dictionary = {'Website': 'Tutorialsrack.com'}
In this program, we used the python dictionary built-in update()
function to update the set, adding from the other iterable to the dictionary and we update the dictionary 1 using the update()
and add another dictionary to dictionary 1.
# Python Program to Add Key-Value Pair to a Dictionary Using update() function with other iterable
# Declaring two dictionaries
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
dict2 = {'Animal': 'Tiger', 'Tree': 'Coconut'}
# Printing dictionary1 and Dictionary2
print("Dictiorary 1: ",dict1)
print("Dictiorary 2: ",dict2)
# Now we will update dict1 with the value of dict2
dict1.update(dict2)
# Now printing new values of dictionary1
print("\nUpdated Dictionary: \n",dict1)
Dictionary 1: {'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}
Dictionary 2: {'Animal': 'Tiger', 'Tree': 'Coconut'}
Updated Dictionary =
{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot', 'Animal': 'Tiger', 'Tree': 'Coconut'}
# Python Program to Add Key-Value Pair to a Dictionary Insert Key-Value into a dictionary
# Take the Input from the user
key = input("Enter the Key: ")
value = input("Enter the Value: ")
myDict = {}
# Add Key-Value Pair to a Dictionary in Python
myDict[key] = value
print("\nUpdated Dictionary = ", myDict)
Enter the Key: website
Enter the Value: rurorialsrack.com
Updated Dictionary = {'website': 'rurorialsrack.com'}
Comments