Consider the following dictionary: (5)
States = [‘D’: ‘Delhi’, ‘K’ : ’Kerala’, ‘T’ : ’Tamil Nadu’, ‘B’ : ‘Bihar’]
Write Python statements for the following. Kindly state the reason for the operations
which not possible.
a. To insert (‘R’ : ‘Red Fort’) and (‘J’ : ‘Jantar Mantar’) in the dictionary states.
b. To replace the value of key ‘K’ by ‘Karnataka’.
c. To remove the element with key ‘B’.
d. To delete the dictionary, states.
e. To display all the elements of a dictionary states in different lines.
Answers
The given dictionary:
States = {‘D’:‘Delhi’, ‘K’:’Kerala’, ‘T’:’Tamil Nadu’, ‘B’:‘Bihar’}
a. To insert ('R':'Red Fort') and ('J':'Jantar Mantar').
To insert new keys and values into a dictionary, follow this format:
b. To replace the value of key 'K' with 'Karnataka'.
To replace the value of a specific key, follow the same method as introducing a new key-value pair, but this time, mentioning the new value with the original key.
c. To remove the element with key 'B'.
del is a function used to delete elements.
d. To delete the dictionary States.
e. To display all the elements of the dictionary in different lines.
To print/traverse through each element, we use a for loop, an iteration statement used to perform repeated checking. We use "\n" to enable a new line between each element.