KnowledgeBoat Logo
|

Computer Science

Create a dictionary named D with three entries, for keys 'a', 'b' and 'c'. What happens if you try to index a nonexistent key (D['d']) ? What does python do if you try to assign to a nonexistent key d.
(e.g., D['d'] = 'spam') ?

Python Dictionaries

4 Likes

Answer

  1. In this example, the dictionary D does not contain the key 'd'. Therefore, attempting to access this key by D['d'] results in a KeyError because the key does not exist in the dictionary.
  2. If we try to assign a value to a nonexistent key in a dictionary, python will create that key-value pair in the dictionary. In this example, the key 'd' did not previously exist in the dictionary D. When we attempted to assign the value 'spam' to the key 'd', python created a new key-value pair 'd': 'spam' in the dictionary D.
D = {'a' : 1, 'b' : 2, 'c' : 3}
D['d'] = 'spam'
Output
D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}

Answered By

3 Likes


Related Questions