Dictionary Methods
'''
Dictionary Methods:
Dictionary uses several built-in methods for manipulation.
1.update()
2.clear()
'''
'''
1.update()
This method updates the value of the key provided to it if the item already exists in the dictionary, else it creates a new value-pair.
'''
ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57}
ep2 = {3583: 61, 9361: 90, 2539: 73, 3748: 44}
ep1.update(ep2)
print(ep1) #output = {2402: 92, 1001: 88, 1806: 45, 2810: 57, 3583: 61, 9361: 90, 2539: 73, 3748: 44}
'''
Removing items from dictionary:
2.clear()
This method clears all the items from the dictionary.
3.pop()
This method removes the key-value pair whose key is passed as a parameter.
4. popitem()
This method removes the last key-value pair from the dictionary.
5.del()
This keyword is used to remove a dictionary item.
'''
ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57}
ep1.clear()
print(ep1) #output = {}
ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57}
ep1.pop(2402)
print(ep1) #output = {1001: 88, 1806: 45, 2810: 57}
ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57}
ep1.popitem()
print(ep1) #output = {2402: 92, 1001: 88, 1806: 45}
ep1 = {2402: 92, 1001: 88, 1806: 45, 2810: 57}
del ep1[1806]
print(ep1) #output = {2402: 92, 1001: 88, 2810: 57}
# del ep1["1806"]
# print(ep1) #output = KeyError: '1806'
#If key is not provided, then the del keyword will delete the dictionary entirely.
# ep2 = {3583: 61, 9361: 90, 2539: 73, 3748: 44}
# del ep2[2402] #output = KeyError: 2402
Comments
Post a Comment