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
- 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.
- 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
Dictionary is a mutable type, which means you can modify its contents ? What all is modifiable in a dictionary ? Can you modify the keys of a dictionary ?
How is
del Danddel D[<key>]different from one another if D is a dictionary ?What is sorting ? Name some popular sorting techniques.
Discuss Bubble sort and Insertion sort techniques.