Given that d refers to a dictionary, change the value mapped to by the key ‘Monty’ to ‘Python’.

Given that d refers to a dictionary, change the value mapped to by the key 'Monty' to 'Python'. Write in Python

Answer

The required statement is as follows:

d['Monty'] = 'Python'

Explanation:

The general syntax to set the value mapped by a key in a dictionary is as follows: dictionary_name[key_var] = value_var

where dictionary_name is the name associated with the dictionary, key_var is the key for which the mapped value is to be set and, the value_var is the value to be set.

If there is already a value mapped by the key_var in dictionary_name then, that value is overridden by value_var. It is given that the required dictionary is associated with the name ‘d’ and, the value mapped by the key ‘Monty’ is to be changed to ‘Python’ Hence, the required statement is as follows:

d['Monty'] = 'Python'

Below is the code to test the working of the above given statement.

  1. #Define a dictionary to test the working of the statement.
  2. d = {'Name1': 'Language1', 'Monty':'Language2', 'Name3': 'Language3'}
  3. #Print the value mapped by the key 'Monty'.
  4. print("Value mapped by the key \'Monty\':",d['Monty'])
  5. #Change the value mapped
  6. #by the key 'Monty' to 'Python'.
  7. d['Monty'] = 'Python'
  8. #Print the value mapped by the key 'Monty'.
  9. print("Value mapped by the key \'Monty\' after the change:",d['Monty'])

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts