Python Dictionary - Subscript Method

Overview of the subscript operator:

  • Using the subscript operator a value corresponding to a key from a Python dictionary instance can be retrieved.
  • A new value can be added to or an existing value can be updated to a Python dictionary instance using the subscript operator.


dict_key_in - The key for which the value to be added/updated/retrieved.

Return Value:

The value corresponding to the dict_key_in parameter is returned in case of retrieval.

Exception Handling:

If the key value is not found in the dictionary a KeyError is raised. For the subclasses of dict, the function __missing__ will be invoked if one is defined. Otherwise, KeyError is raised. 


__missing__ function is typically defined by a subclass to return a default value when the lookup for the key in a Python dictionary fails.   


>>> dict = {'PyCon2016':'Portland-OR','SciPy 2016':'Austin-TX','EuroPython 2016':'Bilbao'}


>>> dict['PyCon2016']



Copyright 2023 ©