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}
- my_dict.get('orange')
- print(my_dict['apple', 'banana'])
- my_dict['apple'] = 20
- print(str(my_dict))
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.
Related Questions
What will be the output of the following code snippet ?
message = "World Peace" print(message[-2::-2])
What will be the output of the following code ?
tuple1 = (1, 2, 3) tuple2 = tuple1 tuple1 += (4, ) print(tuple1 == tuple2)
- True
- False
- tuple1
- Error
What does the list.remove(x) method do in Python ?
- Removes the element at index x from the list
- Removes the first occurrence of value x from the list
- Removes all occurrences of value x from the list
- Removes the last occurrence of value x from the list
If a table which has one Primary key and two alternate keys. How many Candidate keys will this table have ?
- 1
- 2
- 3
- 4