5.7. Mapping Getitem

5.7.1. Rationale

  • Key lookup is very efficient O(1)

  • [...] throws KeyError exception if key not found in dict

  • .get() returns None if key not found

  • .get() can have default value, if key not found

5.7.2. Getitem Method

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>>
>>> crew['commander']
'Melissa Lewis'
>>>
>>> crew['chemist']
Traceback (most recent call last):
KeyError: 'chemist'

5.7.3. Get Method

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>>
>>> crew.get('commander')
'Melissa Lewis'
>>>
>>> crew.get('chemist')
>>>
>>> crew.get('chemist', 'not assigned')
'not assigned'

5.7.4. Key Type

Getting keys other than str:

>>> calendarium = {
...    1961: 'First Human Space Flight',
...    1969: 'First Step on the Moon'}
>>>
>>>
>>> calendarium[1961]
'First Human Space Flight'
>>>
>>> calendarium['1961']
Traceback (most recent call last):
KeyError: '1961'

5.7.5. GetItem

  • GetItem with index on dict is not possible

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>>
>>> crew[0]
Traceback (most recent call last):
KeyError: 0
>>>
>>> crew[1]
Traceback (most recent call last):
KeyError: 1
>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>>
>>> crew[-0]
Traceback (most recent call last):
KeyError: 0
>>>
>>> crew[-1]
Traceback (most recent call last):
KeyError: -1

5.7.6. Slice

  • Slicing on dict is not possible

>>> crew = {
...    'commander': 'Melissa Lewis',
...    'botanist': 'Mark Watney',
...    'pilot': 'Rick Martinez'}
>>>
>>>
>>> crew[1:2]
Traceback (most recent call last):
TypeError: unhashable type: 'slice'
>>>
>>> crew[:2]
Traceback (most recent call last):
TypeError: unhashable type: 'slice'
>>>
>>> crew[::2]
Traceback (most recent call last):
TypeError: unhashable type: 'slice'

5.7.7. GetItem on Numeric Dict Keys

>>> crew = {
...    0: 'Melissa Lewis',
...    1: 'Mark Watney',
...    2: 'Rick Martinez'}
>>>
>>>
>>> crew[0]
'Melissa Lewis'
>>>
>>> crew[1]
'Mark Watney'
>>>
>>> crew[2]
'Rick Martinez'
>>>
>>> crew[-0]
'Melissa Lewis'
>>>
>>> crew[-1]
Traceback (most recent call last):
KeyError: -1
>>>
>>> crew[-2]
Traceback (most recent call last):
KeyError: -2

5.7.8. Assignments