Q:

Python program for adding elements to a dictionary

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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)}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now