Q. 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 a (e.g., D['d']='spam')?
Answer :-
If execute D['d'] then it will give error.
If we execute D['d'] it will add as new key : value pair.
Output :-
>>>D = { 'a' : 1, 'b' : 2, 'c' : 3 }
>>>D[ 'd' ]
>>>Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
D[ 'd' ]
KeyError: 'd'
>>>D['d'] = 'spam'
>>>D
>>>{'a': 1, 'b': 2, 'c': 3, 'd': 'spam'}
>>>Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
D[ 'd' ]
KeyError: 'd'
>>>D['d'] = 'spam'
>>>D
>>>{'a': 1, 'b': 2, 'c': 3, 'd': 'spam'}
The answer wrong it doesn't raise error instead it adds the key:value pair
ReplyDeletePlease try it in your Python.
DeletePost a Comment
You can help us by Clicking on ads. ^_^
Please do not send spam comment : )