Professional Documents
Culture Documents
Project:Dictionary in python
OBJECTIVE
Aim Platform
dictionary
https://www.onlin
egdb.com/ .and
https://colab.rese
arch.google.com/
Introduction: We have already learned about Dictionary, How to use them for different
Data type, different functions of dictionary, accessing and changing dictionary. Now,
Let’s learn about other functions of dictionary.
Dictionary Functions like adding, removing and changing. Loop, Copy and Nested Dictionaries.
Add Dictionary: Adding an item to the dictionary is done by using a new index key and assigning a
value.
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
dictRollNo.pop(3) # Here we removed the third key.
print(dictRollNo)
Output:
Output:
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
del dictRollNo # It will remove the dictionary completely.
print(dictRollNo) #It will show an error message.
clear(): It clears all elements of dictionary but not dictionary.
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
dictRollNo.clear() # This clears all elements of dictionary but dictionary
remains.
print(dictRollNo)
Output:
{}
update(): It helps in updating and adding new element.
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
dictRollNo.update({'6':'Shishir'}) # Update it helps in adding a new element in dictionary and can
also be used for changing element.
print(dictRollNo)
Output:
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
for x in dictRollNo:
print(x) # it will print all the keys
for x in dictRollNo:
print(dictRollNo[x]) # it will print all values
for x in dictRollNo.keys():
print(x) # it will print all keys
for x in dictRollNo.values():
print(x) # it will print all values
for x in dictRollNo.items():
print(x) # it will print both keys and values
Output:
1
2
3
4
5
Rahul
Subhash
Diya
Riha
John
1
2
3
4
5
Rahul
Subhash
Diya
Riha
John
(1, 'Rahul')
(2, 'Subhash')
(3, 'Diya')
(4, 'Riha')
(5, 'John')
# Let's make a copy of the dictionary.
dictRollNo={
1:'Rahul',
2:'Subhash',
3:'Diya',
4:'Riha',
5:'John'
}
#dictRollNo=dictRollNo1 # it will show an error because you can't copy dictionary like
this.
dictRollNoCopy = dictRollNo.copy()
print(dictRollNoCopy)
dictRollNoCopy1=dict(dictRollNo)
print(dictRollNoCopy1)
Output: