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 »





Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.