Saturday, February 25, 2023

Operations on Python Dictionaries

 In previous chapter "python Dictionaries" we have detailed  how to create a python dictionary and insert an element to python dictionary. In this chapter we will look into more operations on python dictionaries. Here we will be using the dictionaries created in previous chapter to demonstrate different operations. Two dictionaries created in previous chapter are as below



Accessing keys and values: 


Accessing Individual Elements:

Dictionary elements are key value pairs, dictionary individual elements are accessed using the keys


Deleting/Removing Dictionary Elements:

Deleting/Removing of elements from dictionary is done using the del keyword. del deletes the key value pair from the dictionary. Dictionary element to be deleted is accessed using the key

eg: del dict[key] 

Element 10 is deleted from the dictionary using the del keyword. Dictionary elements are shown prior and after deletion of element 10.

pop on Dictionary Element:

pop deletes key value pair from dictionary and returns the value of the deleted element. Dictionary element to pop is accessed using the key.

eg: dict.pop(key)

In above example element A is popped from dict2 and value of A is returned after pop operation

update on Dictionary Element:

update keyword inserts a new element if key is not present in the element list. value of key is updated when element exists in the dictionary. Dictionary does not support duplicate keys.

eg: dict.update({key:value})


Renaming Dictionary Key:

To achieve this functionality, use pop operation which deletes the element and returns value of that key. Using the value returned during pop operation, insert a new element to dictionary.



Operations on Python Dictionaries