KnowledgeBoat Logo

Computer Science

If my_dict is a dictionary as defined below, then which of the following statements will raise an exception ?

my_dict = {'apple' : 10, 'banana' : 20, 'orange' : 30}

  1. my_dict.get('orange')
  2. print(my_dict['apple', 'banana'])
  3. my_dict['apple'] = 20
  4. print(str(my_dict))

Python Dictionaries

7 Likes

Answer

print(my_dict['apple', 'banana'])

Reason — In Python dictionaries, keys must be accessed individually or as a single key. The expression my_dict['apple', 'banana'] attempts to use a tuple as a key (i.e., ('apple', 'banana')), which does not exist in my_dict. As a result, this will raise an Error. The other statements will not raise exceptions; my_dict.get('orange') will return 30, my_dict['apple'] = 20 will update the value for the key 'apple', and print(str(my_dict)) will print the dictionary as a string.

Answered By

2 Likes


Related Questions