Home »
Python »
Python programs
Python program for adding elements to a dictionary
Here, we are going to learn how to add elements to a dictionary? Also, writing a Python program to add elements to a dictionary.
Submitted by Shivang Yadav, on March 21, 2021
There are multiple ways to add elements to a dictionary – The one method is to add a single value by defining value along with the key.
dict_name[key] = value
Program to add elements to a dictionary in Python
# Creating an empty Dictionary
Record = {}
print("The Dictionary is: ")
print(Record)
# Adding one element at a time
Record[0] = 'Amit'
Record[1] = 'Kumar'
Record[2] = 21
Record[3] = 'Delhi'
print("\nNow, the Dictionary is: ")
print(Record)
# adding multiple values to a key
Record['marks'] = 69, 70, 58
print("\nNow, the Dictionary is: ")
print(Record)
# Updating an existing Key's Value
Record[2] = 23
print("\nNow, the Dictionary is: ")
print(Record)
# Adding Nested Key value
Record[4] = {'Nested' :{'Name' : 'Shivang', 'Age' : 24}}
print("\nNow, the Dictionary is: ")
print(Record)
Output:
The Dictionary is:
{}
Now, the Dictionary is:
{0: 'Amit', 1: 'Kumar', 2: 21, 3: 'Delhi'}
Now, the Dictionary is:
{0: 'Amit', 1: 'Kumar', 2: 21, 3: 'Delhi', 'marks': (69, 70, 58)}
Now, the Dictionary is:
{0: 'Amit', 1: 'Kumar', 2: 23, 3: 'Delhi', 'marks': (69, 70, 58)}
Now, the Dictionary is:
{0: 'Amit', 1: 'Kumar', 2: 23, 3: 'Delhi',
4: {'Nested': {'Name': 'Shivang', 'Age': 24}}, 'marks': (69, 70, 58)}
Python Dictionary Programs »