7.3. Mapping Getitem

  • 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

>>> hello = {
...    'English': 'Hello',
...    'German': 'Guten Tag',
...    'Polish': 'Witaj',
... }
>>>
>>>
>>> hello.get('English')
'Hello'
>>>
>>> hello.get('Polish')
'Witaj'

7.3.1. 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'

7.3.2. 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'

7.3.3. Switch

Simulate user input (for test automation):

>>> from unittest.mock import MagicMock
>>> input = MagicMock(side_effect=['French'])
>>> hello = {
...     'English': 'Hello',
...     'German': 'Guten Tag',
...     'Polish': 'Witaj',
...     'default': "I don't speak this language",
... }
>>>
>>>
>>> language = input('What is your language?: ')  #input: 'French'
>>> result = hello.get(language, hello['default'])
>>>
>>> print(result)
I don't speak this language

7.3.4. Use Case - 0x01

>>> MONTHS = {
...     1: 'January',
...     2: 'February',
...     3: 'March',
... }
>>>
>>> MONTHS[1]
'January'
>>>
>>> MONTHS['1']
Traceback (most recent call last):
KeyError: '1'
>>>
>>> MONTHS['01']
Traceback (most recent call last):
KeyError: '01'

7.3.5. Use Case - 0x02

>>> MONTHS = {
...     1: 'January',
...     2: 'February',
...     3: 'March',
... }
>>>
>>> MONTHS.get(1)
'January'
>>>
>>> MONTHS.get(13)
>>>
>>> MONTHS.get(13, 'invalid month')
'invalid month'

7.3.6. Use Case - 0x03

>>> MONTHS = {
...     1: 'January',
...     2: 'February',
...     3: 'March',
...     4: 'April',
...     5: 'May',
...     6: 'June',
...     7: 'July',
...     8: 'August',
...     9: 'September',
...     10: 'October',
...     11: 'November',
...     12: 'December'
... }
>>>
>>> DATE = '1961-04-12'
>>>
>>> year, month, day = DATE.split('-')
>>>
>>> year
'1961'
>>> month
'04'
>>> day
'12'
>>>
>>> MONTHS[month]
Traceback (most recent call last):
KeyError: '04'
>>>
>>> MONTHS[int(month)]
'April'

7.3.7. Use Case - 0x04

>>> PAYROLL = [
...     {'name': 'Mark Watney',   '2000-01': 2000, '2000-02': 2000, '2000-03': 2000},
...     {'name': 'Melissa Lewis', '2000-01': 3000, '2000-02': 3000, '2000-03': 3000},
...     {'name': 'Rick Martinez', '2000-03': 2500},
...     {'name': 'Alex Vogel',    '2000-01': 2500, '2000-02': 2500, '2000-03': 2500},
... ]
>>> result = f'{"Employee":<15} {"January":>10} {"February":>9} {"March":>6}'
>>>
>>> for employee in PAYROLL:
...     name = employee['name']
...     january = employee['2000-01']
...     february = employee['2000-02']
...     march = employee['2000-03']
...     result += f'{name:<15} {january:>10} {february:>9} {march:>6}'
...
Traceback (most recent call last):
KeyError: '2000-01'
>>> result = f'{"Employee":<15} {"January":>10} {"February":>9} {"March":>6}\n'
>>>
>>> for employee in PAYROLL:
...     name = employee['name']
...     january = employee.get('2000-01', 'n/a')
...     february = employee.get('2000-02', 'n/a')
...     march = employee.get('2000-03', 'n/a')
...     result += f'{name:<15} {january:>10} {february:>9} {march:>6}\n'
>>>
>>> print(result)
Employee           January  February  March
Mark Watney           2000      2000   2000
Melissa Lewis         3000      3000   3000
Rick Martinez          n/a       n/a   2500
Alex Vogel            2500      2500   2500
>>> result = f'{"Employee":<15} {"January":>10} {"February":>9} {"March":>6}\n'
>>>
>>> for employee in PAYROLL:
...     name = employee['name']
...     january = employee.get('2000-01', '-')
...     february = employee.get('2000-02', '-')
...     march = employee.get('2000-03', '-')
...     result += f'{name:<15} {january:>10} {february:>9} {march:>6}\n'
>>>
>>> print(result)
Employee           January  February  March
Mark Watney           2000      2000   2000
Melissa Lewis         3000      3000   3000
Rick Martinez            -         -   2500
Alex Vogel            2500      2500   2500
>>> result = f'{"Employee":<15} {"January":>10} {"February":>9} {"March":>6}\n'
>>>
>>> for employee in PAYROLL:
...     name = employee['name']
...     january = employee.get('2000-01', '')
...     february = employee.get('2000-02', '')
...     march = employee.get('2000-03', '')
...     result += f'{name:<15} {january:>10} {february:>9} {march:>6}\n'
>>>
>>> print(result)
Employee           January  February  March
Mark Watney           2000      2000   2000
Melissa Lewis         3000      3000   3000
Rick Martinez                          2500
Alex Vogel            2500      2500   2500

7.3.8. Assignments

"""
* Assignment: Mapping Dict Getitem
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Use `DATA: dict`
    2. Define `result: str` with value for key 'firstname' from `DATA`
    3. Use getitem syntax
    4. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict`
    2. Zdefiniuj `result: str` z wartością dla klucza 'firstname' z `DATA`
    3. Użyj składni getitem
    4. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * dict[key]

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> pprint(result)
    'Mark'
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Define `result: str` with value for key 'firstname' from `DATA`
# Use getitem syntax
# type: str
...

"""
* Assignment: Mapping Dict Get
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Use `DATA: dict`
    2. Define `result: str` with value for key 'firstname'
    3. Use `get` method
    4. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict`
    2. Zdefiniuj `result: str` z wartością dla klucza 'firstname'
    3. Użyj metodę `get`
    4. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * dict.get(key)

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> pprint(result)
    'Mark'
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Define `result: str` with value for key 'firstname'
# Use `get` method
# type: str
...

"""
* Assignment: Mapping Dict GetDefault
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Use `DATA: dict`
    2. Define `result: str` with value for key 'email'
    3. If value does not exist in dict, return 'n/a'
    4. Use `get` method with default value
    5. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict`
    2. Zdefiniuj `result: str` z wartością dla klucza 'email'
    3. Jeżeli wartość nie istnieje w dict, zwróć 'n/a'
    4. Użyj metody `get` z wartością domyślną
    5. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * dict.get(key, default)

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> pprint(result)
    'n/a'
"""

DATA = {
    'firstname': 'Mark',
    'lastname': 'Watney',
    'group': 'users',
}

# Define `result: str` with value for key 'email'
# If value does not exist in dict, return 'n/a'
# Use `get` method with default value
# type: str
...

"""
* Assignment: Mapping Dict Switch
* Type: class assignment
* Complexity: medium
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Use `DATA: dict` - with pilot's phonetic alphabet
    2. Ask user to input letter
    3. Define `result: str` with phonetic pronunciation of a letter
    4. If character not existing in alphabet, assign: 'Missing'
    5. Non-functional requirements:
        a. User will always put only one capitalized letter
        b. User will not input any invalid characters or numbers
        c. Do not use `if`, `try`, and `except`
        d. `Mock` will simulate inputting `W` letter by a user
        e. Use `input()` function as normal
    6. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict` - alfabet fonetyczny pilotów
    2. Poproś użytkownika o wprowadzenie litery
    3. Zdefiniuj `result: str` z fonetyczną wymową litery
    4. Jeżeli znak nie istnieje w alfabecie, przypisz: 'Missing'
    5. Wymagania niefunkcjonalne:
        a. Użytkownik zawsze wpisze tylko jedną wielką literę lub cyfrę
        b. Nie używaj `if`, `try`, i `except`
        c. `Mock` zasymuluje wpisanie litery `W` przez użytkownika
        d. Skorzytaj z funkcji `input()` tak jak normalnie
    6. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * input(prompt)

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint
    >>> import string

    >>> assert letter is not Ellipsis, \
    'Ask user to input letter and assign it to: `letter`'
    >>> assert result is not Ellipsis, \
    'Assign your result to variable `result`'
    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> pprint(result)
    'Whisky'
"""

# Simulate user input (for test automation)
from unittest.mock import Mock
input = Mock(return_value='W')


DATA = {
    'A': 'Alfa',
    'B': 'Bravo',
    'C': 'Charlie',
    'D': 'Delta',
    'E': 'Echo',
    'F': 'Foxtrot',
    'G': 'Golf',
    'H': 'Hotel',
    'I': 'India',
    'J': 'Juliet',
    'K': 'Kilo',
    'L': 'Lima',
    'M': 'Mike',
    'N': 'November',
    'O': 'Oscar',
    'P': 'Papa',
    'Q': 'Quebec',
    'R': 'Romeo',
    'S': 'Sierra',
    'T': 'Tango',
    'U': 'Uniform',
    'V': 'Victor',
    'W': 'Whisky',
    'X': 'X-Ray',
    'Z': 'Zulu',
}

# Ask user to input letter
# type: str
letter = ...

# Define `result: str` with phonetic pronunciation of a letter
# If character not existing in alphabet, assign: 'Missing'
# type: str
result = ...

"""
* Assignment: Mapping Dict SwitchMatches
* Type: class assignment
* Complexity: medium
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Use `DATA: dict` with Polish diacritic characters
    2. Ask user to input single letter
    3. Convert letter to lowercase
    4. If letter is in `DATA` then use conversion value for the letter
    5. Non-functional requirements:
        a. User will always put only one capitalized letter
        b. User will not input any invalid characters or numbers
        c. Do not use `if`, `try`, and `except`
        d. Use `input()` function as normal
        e. `Mock` will simulate inputting `Ó` letter by a user
        f. Note that letter `Ó` is in `DATA`
    6. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict` z polskimi znakami diakrytycznymi
    2. Poproś użytkownika o wprowadzenie pojedynczej litery
    3. Zamień literę na małą
    4. Jeżeli litera jest w `DATA` to użyj wartości konwersji dla litery
    5. Wymagania niefunkcjonalne:
        a. Użytkownik zawsze wpisze tylko jedną wielką literę
        b. Użytkownik nie wpisze żadnych nieprawidłowych znaków lub cyfr
        c. Nie używaj `if`, `try`, i `except`
        d. Skorzytaj z funkcji `input()` tak jak normalnie
        e. `Mock` zasymuluje wpisanie litery `Ó` przez użytkownika
        f. Zwróć uwagę, że litera `Ó` jest w `DATA`
    6. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * input()
    * str.lower()

Example:
    | Input | Output |
    |-------|--------|
    |   a   |    a   |
    |   A   |    a   |
    |   ą   |    a   |
    |   Ą   |    a   |
    |   b   |    b   |
    |   B   |    B   |
    |   c   |    c   |
    |   C   |    c   |
    |   ć   |    c   |
    |   Ć   |    c   |
    |  ...  |   ...  |

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint
    >>> import string

    >>> assert letter is not Ellipsis, \
    'Ask user to input letter and assign it to: `letter`'
    >>> assert result is not Ellipsis, \
    'Assign your result to variable `result`'
    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'
    >>> assert result not in PL.keys(), \
    'Result should not be in DATA dict'
    >>> assert result in string.ascii_letters, \
    'Result should be an ASCII letter'

    >>> pprint(result)
    'o'
"""

# Simulate user input (for test automation)
from unittest.mock import Mock
input = Mock(side_effect=['Ó'])


PL = {
    'ą': 'a',
    'ć': 'c',
    'ę': 'e',
    'ł': 'l',
    'ń': 'n',
    'ó': 'o',
    'ś': 's',
    'ż': 'z',
    'ź': 'z',
}

# Ask user to input single letter
# Convert letter to lowercase
# type: str
letter = ...

# If letter is in `DATA` then use conversion value for the letter
# type: str
result = ...

"""
* Assignment: Mapping Dict SwitchMissing
* Type: class assignment
* Complexity: medium
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Use `DATA: dict` with Polish diacritic characters
    2. Ask user to input single letter
    3. Convert letter to lowercase
    4. If letter is in `DATA` then use conversion value for the letter
    5. Non-functional requirements:
        a. User will always put only one capitalized letter
        b. User will not input any invalid characters or numbers
        c. Do not use `if`, `try`, and `except`
        d. Use `input()` function as normal
        e. `Mock` will simulate inputting `O` letter by a user
        f. Note that letter `O` is not in `DATA`
    6. Run doctests - all must succeed

Polish:
    1. Użyj `DATA: dict` z polskimi znakami diakrytycznymi
    2. Poproś użytkownika o wprowadzenie pojedynczej litery
    3. Zamień literę na małą
    4. Jeżeli litera jest w `DATA` to użyj wartości konwersji dla litery
    5. Wymagania niefunkcjonalne:
        a. Użytkownik zawsze wpisze tylko jedną wielką literę
        b. Użytkownik nie wpisze żadnych nieprawidłowych znaków lub cyfr
        c. Nie używaj `if`, `try`, i `except`
        d. Skorzytaj z funkcji `input()` tak jak normalnie
        e. `Mock` zasymuluje wpisanie litery `O` przez użytkownika
        f. Zwróć uwagę, że litera `O` nie jest w `DATA`
    6. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * input()
    * str.lower()

Example:
    | Input | Output |
    |-------|--------|
    |   a   |    a   |
    |   A   |    a   |
    |   ą   |    a   |
    |   Ą   |    a   |
    |   b   |    b   |
    |   B   |    B   |
    |   c   |    c   |
    |   C   |    c   |
    |   ć   |    c   |
    |   Ć   |    c   |
    |  ...  |   ...  |

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from pprint import pprint
    >>> import string

    >>> assert letter is not Ellipsis, \
    'Ask user to input letter and assign it to: `letter`'
    >>> assert result is not Ellipsis, \
    'Assign your result to variable `result`'
    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'
    >>> assert result not in PL.keys(), \
    'Result should not be in DATA dict'
    >>> assert result in string.ascii_letters, \
    'Result should be an ASCII letter'

    >>> pprint(result)
    'o'
"""

# Simulate user input (for test automation)
from unittest.mock import Mock
input = Mock(side_effect=['O'])


PL = {
    'ą': 'a',
    'ć': 'c',
    'ę': 'e',
    'ł': 'l',
    'ń': 'n',
    'ó': 'o',
    'ś': 's',
    'ż': 'z',
    'ź': 'z',
}

# Ask user to input single letter
# Convert letter to lowercase
# type: str
letter = ...

# If letter is in `DATA` then use conversion value for the letter
# type: str
result = ...