Will an error always occur when trying to access a key that doesn't exist?


#1

Question

Will an error always be generated when trying to access a key which doesn’t exist in a dictionary?

Answer

Yes, an error will always be generated so care must be taken to check that the key exists OR exception handling must be used to handle an exception generated by the invalid key. If iterating over the keys in a dictionary provided by the keys() function, then it is safe to assume the key exists.