what is a dictionary?

A dictionary also known as a Mapping is a way to keep key-value pairs. The values can be any Python object. I add tests to see which of the Python basic data types I can use as keys .

I think this is the most important data structure because it can hold all the others, same as with lists and tuples. In programming I have had to work with JSON which I can read and write as dictionaries.


preview

I have these tests by the end of the chapter

dictionaries/tests/test_dictionaries.py
 1import unittest
 2
 3
 4class TestDictionaries(unittest.TestCase):
 5
 6    def test_making_a_dictionary(self):
 7        self.assertEqual(dict(), {})
 8        self.assertEqual(dict(key='value'), {'key': 'value'})
 9
10    def test_making_a_dictionary_w_none_as_a_key(self):
11        self.assertEqual({None: 'boom'}, {None: 'boom'})
12
13    def test_making_a_dictionary_w_a_boolean_as_a_key(self):
14        self.assertEqual(
15            {False: 'boom', True: 'bap'},
16            {False: 'boom', True: 'bap'}
17        )
dictionaries/tests/test_dictionaries.py
19    def test_making_a_dictionary_w_a_number_as_a_key(self):
20        self.assertEqual(
21            {0: 'boom', 0.1: 'bap'},
22            {0: 'boom', 0.1: 'bap'}
23        )
24
25    def test_making_a_dictionary_w_a_tuple_as_a_key(self):
26        self.assertEqual(
27            {(0, 1): 'boom'},
28            {(0, 1): 'boom'}
29        )
dictionaries/tests/test_dictionaries.py
31    def test_making_a_dictionary_w_a_list_as_a_key(self):
32        with self.assertRaises(TypeError):
33            {[3, 2, 1]: 'BOOM!!!'}
34
35    def test_making_a_dictionary_w_a_set_as_a_key(self):
36        with self.assertRaises(TypeError):
37            {{3, 2, 1}: 'BOOM!!!'}
38
39    def test_making_a_dictionary_w_a_dictionary_as_a_key(self):
40        a_dictionary = {'key': 'value'}
41        with self.assertRaises(TypeError):
42            {a_dictionary: 'BOOM!!!'}
dictionaries/tests/test_dictionaries.py
44    def test_dir_dict(self):
45        self.maxDiff = None
46        dir_dict = dir(object)
47        dir_dict.extend((
48            '__class_getitem__', '__contains__',
49            '__delitem__', '__getitem__', '__ior__',
50            '__iter__', '__len__', '__or__',
51            '__reversed__', '__ror__', '__setitem__',
52            'clear', 'copy', 'fromkeys',
53            'get', 'items', 'keys',
54            'pop', 'popitem', 'setdefault',
55            'update', 'values'
56        ))
57        dir_dict.sort()
58        self.assertEqual(
59            dir(dict),
60            dir_dict
61        )
dictionaries/tests/test_dictionaries.py
63    def test_clear_empties_a_dictionary(self):
64        a_dictionary = {'key': 'value'}
65        self.assertIsNone(a_dictionary.clear())
66        self.assertEqual(a_dictionary, {})
67
68    def test_copy_a_dictionary(self):
69        a_dictionary = {'key': 'value'}
70        self.assertEqual(
71            a_dictionary.copy(),
72            {'key': 'value'}
73        )
dictionaries/tests/test_dictionaries.py
75    def test_fromkeys_makes_a_dictionary_from_an_iterable(self):
76        self.assertEqual(
77            dict.fromkeys((0, 1)),
78            {0: None, 1: None}
79        )
80        self.assertEqual(
81            dict.fromkeys((0, 1), 'default'),
82            {0: 'default', 1: 'default'}
83        )
84        self.assertEqual(
85            {key: 'value' for key in (0, 1)},
86            {0: 'value', 1: 'value'}
87        )
dictionaries/tests/test_dictionaries.py
 89    def test_get_value_of_a_key_in_a_dictionary(self):
 90        a_dictionary = {'key': 'value'}
 91        self.assertIsNone(
 92            a_dictionary.get('not in dictionary')
 93        )
 94        self.assertEqual(
 95            a_dictionary.get(
 96                'not in dictionary', 'default'
 97            ),
 98            'default'
 99        )
100        self.assertEqual(
101            a_dictionary.get('key', 'default'),
102            'value'
103        )
dictionaries/tests/test_dictionaries.py
105    def test_items_returns_iterable_of_key_value_pairs_of_a_dictionary(self):
106        a_dictionary = {
107            'key0': 'value0',
108            'keyN': [0, 1, 2, 'n'],
109        }
110        self.assertEqual(
111            list(a_dictionary.items()),
112            [
113                ('key0', 'value0'),
114                ('keyN', [0, 1, 2, 'n']),
115            ]
116        )
dictionaries/tests/test_dictionaries.py
118    def test_keys_of_a_dictionary(self):
119        a_dictionary = {
120            'key0': 'value0',
121            'keyN': [0, 1, 2, 'n'],
122        }
123        self.assertEqual(
124            list(a_dictionary.keys()),
125            ['key0', 'keyN']
126        )
dictionaries/tests/test_dictionaries.py
128    def test_pop_removes_given_key_from_a_dictionary_and_returns_its_value(self):
129        a_dictionary = {'key': 'value'}
130
131        with self.assertRaises(KeyError):
132            a_dictionary.pop('not_in_dictionary')
133
134        self.assertIsNone(
135            a_dictionary.pop('not_in_dictionary',  None)
136        )
137        self.assertEqual(
138            a_dictionary.pop('not_in_dictionary', 'default'),
139            'default'
140        )
141        self.assertEqual(
142            a_dictionary.pop('key', 'default'),
143            'value'
144        )
145        self.assertEqual(a_dictionary, {})
dictionaries/tests/test_dictionaries.py
147    def test_popitem_removes_and_returns_last_key_value_pair_from_a_dictionary(self):
148        a_dictionary = {
149            'key0': 'value0',
150            'keyN': [0, 1, 2, 'n'],
151        }
152        self.assertEqual(
153            a_dictionary.popitem(),
154            ('keyN', [0, 1, 2, 'n'])
155        )
156        self.assertEqual(a_dictionary, {'key0': 'value0'})
dictionaries/tests/test_dictionaries.py
158    def test_setdefault_adds_given_key_to_a_dictionary(self):
159        a_dictionary = {'key': 'value'}
160        self.assertEqual(
161            a_dictionary.setdefault('new_key', 'new value'),
162            'new value'
163        )
164        self.assertEqual(
165            a_dictionary.setdefault('key', 'default'),
166            'value'
167        )
168        self.assertEqual(
169            a_dictionary,
170            {
171                'key': 'value',
172                'new_key': 'new value',
173            }
174        )
dictionaries/tests/test_dictionaries.py
176    def test_update_a_dictionary(self):
177        a_dictionary = {'key': 'value'}
178
179        for key, value in (
180            ('key', 'updated value'),
181            ('new_key', [0, 1, 2, 'n']),
182            ('another_key', {0, 1, 2, 'n'}),
183        ):
184            self.assertIsNone(
185                a_dictionary.update({key: value})
186            )
187
188        self.assertEqual(
189            a_dictionary,
190            {
191                'key': 'updated value',
192                'new_key': [0, 1, 2, 'n'],
193                'another_key': {0, 1, 2, 'n'},
194            }
195        )
dictionaries/tests/test_dictionaries.py
197    def test_values_of_a_dictionary(self):
198        a_dictionary = {
199            'key0': 'value0',
200            'keyN': [0, 1, 2, 'n'],
201        }
202        self.assertEqual(
203            list(a_dictionary.values()),
204            ['value0', [0, 1, 2, 'n']]
205        )
dictionaries/tests/test_dictionaries.py
207    def test_key_error(self):
208        a_dictionary = {'key': 'value'}
209        self.assertEqual(
210            a_dictionary['key'], 'value'
211        )
212
213        with self.assertRaises(KeyError):
214            a_dictionary['not_in_dictionary']
215        self.assertEqual(
216            a_dictionary.get(
217                'not_in_dictionary', 'default'
218            ),
219            'default'
220        )
221
222        with self.assertRaises(KeyError):
223            a_dictionary.pop('not_in_dictionary')
224        self.assertEqual(
225            a_dictionary.pop(
226                'not_in_dictionary', 'default'
227            ),
228            'default'
229        )
230
231        with self.assertRaises(KeyError):
232            {}.popitem()
233
234
235# Exceptions seen
236# AssertionError
237# TypeError
238# NameError
239# KeyError

questions about dictionaries

start the project

  • I open a terminal

  • I give dictionaries as the first argument to the makePythonTdd program

    terminal
    ./makePythonTdd.sh dictionaries
    
    terminal
    .\makePythonTdd.ps1 dictionaries
    

    the terminal is my friend, and shows AssertionError

    terminal
    ======================== FAILURES ==========================
    ______________ Testdictionaries.test_failure _________________
    
    self = <tests.test_dictionaries.Testdictionaries testMethod=test_failure>
    
        def test_failure(self):
    >       self.assertFalse(True)
    E       AssertionError: True is not false
    
    tests/test_dictionaries.py:7: AssertionError
    ================== short test summary info ==================
    FAILED tests/test_dictionaries.py::Testdictionaries::test_failure - AssertionError: True is not false
    ===================== 1 failed in X.YZs =====================
    
  • I open test_dictionaries.py from the tests folder then put the cursor on line 7

  • I change assertFalse to assertTrue

    dictionaries/tests/test_dictionaries.py
     4class Testdictionaries(unittest.TestCase):
     5
     6    def test_failure(self):
     7        # self.assertFalse(True)
     8        self.assertTrue(True)
     9
    10
    11# Exceptions seen
    

    the test passes.

  • I change Testdictionaries to TestDictionaries to match Python convention

    dictionaries/tests/test_dictionaries.py
    1import unittest
    2
    3
    4class TestDictionaries(unittest.TestCase):
    5
    6    def test_failure(self):
    
  • I open a new terminal then change directory to dictionaries

    terminal
    cd dictionaries
    
  • I add the new files and folder to git for tracking

    terminal
    git add .
    
  • I add a git commit message

    terminal
    git commit -am 'setup project'
    

test_making_a_dictionary

RED: make it fail


I change test_failure to test_making_a_dictionary then add an assertion

dictionaries/tests/test_dictionaries.py
1import unittest
2
3
4class TestDictionaries(unittest.TestCase):
5
6    def test_making_a_dictionary(self):
7        self.assertEqual(dict(), None)

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {} != None

GREEN: make it pass


I change the expectation to match

dictionaries/tests/test_dictionaries.py
 6    def test_making_a_dictionary(self):
 7        self.assertEqual(dict(), {})
 8
 9
10# Exceptions seen

the test passes. These are two ways to make an empty dictionary

  • the dict constructor - dict()

  • curly braces - {}


REFACTOR: make it better


  • I add an assertion for a dictionary with things in it

    dictionaries/tests/test_dictionaries.py
     6    def test_making_a_dictionary(self):
     7        self.assertEqual(dict(), {})
     8        self.assertEqual(dict(0), {})
     9
    10
    11# Exceptions seen
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: 'int' object is not iterable
    
  • I add TypeError to the list of Exceptions seen

    dictionaries/tests/test_dictionaries.py
    11# Exceptions seen
    12# AssertionError
    13# TypeError
    
  • I change the value given to dict() to a tuple

    dictionaries/tests/test_dictionaries.py
     7        self.assertEqual(dict(), {})
     8        self.assertEqual(dict((0, 1)), {})
     9
    10
    11# Exceptions seen
    

    the terminal is my friend, and shows TypeError

    TypeError: cannot convert dictionary update
               sequence element #0 to a sequence
    
  • I try a keyword argument

    dictionaries/tests/test_dictionaries.py
    7        self.assertEqual(dict(), {})
    8        self.assertEqual(dict(key='value'), {})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value'} != {}
    
  • I change the expectation to match the values in the terminal

    dictionaries/tests/test_dictionaries.py
     6    def test_making_a_dictionary(self):
     7        self.assertEqual(dict(), {})
     8        self.assertEqual(dict(key='value'), {'key': 'value'})
     9
    10
    11# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am 'add test_making_a_dictionary'
    

I know how to make a dictionary.

I used a string as a key in this test. Next I test other Python basic data types to see which ones I can use as keys.


test_making_a_dictionary_w_none_as_a_key

RED: make it fail


I add a test to see if I can use None as a key in a dictionary

dictionaries/tests/test_dictionaries.py
 8        self.assertEqual(dict(key='value'), {'key': 'value'})
 9
10    def test_making_a_dictionary_w_none_as_a_key(self):
11        self.assertEqual({None: 'boom'}, {None: 'bap'})
12
13
14# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {None: 'boom'} != {None: 'bap'}

GREEN: make it pass


  • I change 'bap' to 'boom'

    dictionaries/tests/test_dictionaries.py
    10    def test_making_a_dictionary_w_none_as_a_key(self):
    11        self.assertEqual({None: 'boom'}, {None: 'boom'})
    12
    13
    14# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am 'add test_making_a_dictionary_w_none_as_a_key'
    

I can use strings and None as keys in a dictionary


test_making_a_dictionary_w_a_boolean_as_a_key

RED: make it fail


I add a test to see if I can use a boolean as a key in a dictionary

dictionaries/tests/test_dictionaries.py
11        self.assertEqual({None: 'boom'}, {None: 'boom'})
12
13    def test_making_a_dictionary_w_a_boolean_as_a_key(self):
14        self.assertEqual({False: 'boom'}, {False: 'bap'})
15
16
17# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {False: 'boom'} != {False: 'bap'}

GREEN: make it pass


  • I change 'bap' to 'boom'

    dictionaries/tests/test_dictionaries.py
    13    def test_making_a_dictionary_w_a_boolean_as_a_key(self):
    14        self.assertEqual({False: 'boom'}, {False: 'boom'})
    15
    16
    17# Exceptions seen
    

    the test passes.

I can use False as a key in a dictionary


REFACTOR: make it better


  • I add an assertion for the other boolean

    dictionaries/tests/test_dictionaries.py
    13    def test_making_a_dictionary_w_a_boolean_as_a_key(self):
    14        self.assertEqual(
    15            {False: 'boom', True: 'bap'},
    16            {False: 'boom'}
    17        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {False: 'boom', True: 'bap'} != {False: 'boom'}
    
  • I add the new key-value pair to the expectation

    dictionaries/tests/test_dictionaries.py
    13    def test_making_a_dictionary_w_a_boolean_as_a_key(self):
    14        self.assertEqual(
    15            {False: 'boom', True: 'bap'},
    16            {False: 'boom', True: 'bap'}
    17        )
    18
    19
    20# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_boolean_as_a_key'
    

I can use strings, booleans and None as keys in a dictionary.


test_making_a_dictionary_w_a_number_as_a_key

RED: make it fail


I add a failing test to see if I can use a number as a key in a dictionary

dictionaries/tests/test_dictionaries.py
16            {False: 'boom', True: 'bap'}
17        )
18
19    def test_making_a_dictionary_w_a_number_as_a_key(self):
20        self.assertEqual(
21            {0: 'boom'},
22            {0: 'bap'}
23        )
24
25
26# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {0: 'boom'} != {0: 'bap'}

GREEN: make it pass


I change 'bap' to 'boom'

dictionaries/tests/test_dictionaries.py
19    def test_making_a_dictionary_w_a_number_as_a_key(self):
20        self.assertEqual(
21            {0: 'boom'},
22            {0: 'boom'}
23        )
24
25
26# Exceptions seen

the test passes.

I can use an integer as a key in a dictionary.


REFACTOR: make it better


  • I want to see if I can use a float as a key in a dictionary. I add a float to the dictionary

    dictionaries/tests/test_dictionaries.py
    19    def test_making_a_dictionary_w_a_number_as_a_key(self):
    20        self.assertEqual(
    21            {0: 'boom', 0.1: 'bap'},
    22            {0: 'boom'}
    23        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {0: 'boom', 0.1: 'bap'} != {0: 'boom'}
    
  • I add the new key-value pair to the expectation

    dictionaries/tests/test_dictionaries.py
    19    def test_making_a_dictionary_w_a_number_as_a_key(self):
    20        self.assertEqual(
    21            {0: 'boom', 0.1: 'bap'},
    22            {0: 'boom', 0.1: 'bap'}
    23        )
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_number_as_a_key'
    

I can use strings, numbers (floats and integers), booleans and None as keys in a dictionary.


test_making_a_dictionary_w_a_tuple_as_a_key

RED: make it fail


I add a test to see if I can use a tuple (anything in parentheses (()) separated by a comma) as a key in a dictionary

dictionaries/tests/test_dictionaries.py
20        self.assertEqual(
21            {0: 'boom', 0.1: 'bap'},
22            {0: 'boom', 0.1: 'bap'}
23        )
24
25    def test_making_a_dictionary_w_a_tuple_as_a_key(self):
26        self.assertEqual(
27            {(0, 1): 'boom'},
28            {(0, 1): 'bap'}
29        )
30
31
32# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {(0, 1): 'boom'} != {(0, 1): 'bap'}

GREEN: make it pass


  • I change 'bap' to 'boom'

    dictionaries/tests/test_dictionaries.py
    25    def test_making_a_dictionary_w_a_tuple_as_a_key(self):
    26        self.assertEqual(
    27            {(0, 1): 'boom'},
    28            {(0, 1): 'boom'}
    29        )
    30
    31
    32# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_tuple_as_a_key'
    

I can use tuples, strings, numbers (floats and integers), booleans and None as keys in a dictionary.


test_making_a_dictionary_w_a_list_as_a_key

RED: make it fail


I add a test for making a dictionary with a list (anything in square brackets ([])) as a key

dictionaries/tests/test_dictionaries.py
26        self.assertEqual(
27            {(0, 1): 'boom'},
28            {(0, 1): 'boom'}
29        )
30
31    def test_making_a_dictionary_w_a_list_as_a_key(self):
32        self.assertEqual(
33            {[0, 1]: 'boom'},
34        )
35
36
37# Exceptions seen

the terminal is my friend, and shows TypeError

terminal
TypeError: cannot use 'list' as a dict key
           (unhashable type: 'list')

GREEN: make it pass


  • I remove the things around the new dictionary then change the key and value for fun

    dictionaries/tests/test_dictionaries.py
    31    def test_making_a_dictionary_w_a_list_as_a_key(self):
    32
    33            {[3, 2, 1]: 'BOOM!!!'}
    34
    35
    36# Exceptions seen
    

    the terminal still shows TypeError

  • I add assertRaises

    dictionaries/tests/test_dictionaries.py
    31    def test_making_a_dictionary_w_a_list_as_a_key(self):
    32        with self.assertRaises(TypeError):
    33            {[3, 2, 1]: 'BOOM!!!'}
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_list_as_a_key'
    

I cannot use a list as a key in a dictionary.


test_making_a_dictionary_w_a_set_as_a_key

RED: make it fail


I add a test with a set (single items in curly braces ({})) as a key in a dictionary

dictionaries/tests/test_dictionaries.py
32        with self.assertRaises(TypeError):
33            {[3, 2, 1]: 'BOOM!!!'}
34
35    def test_making_a_dictionary_w_a_set_as_a_key(self):
36        {{3, 2, 1}: 'BOOM!!!'}
37
38
39# Exceptions seen

the terminal is my friend, and shows TypeError

terminal
TypeError: unhashable type: 'set'

GREEN: make it pass


  • I add assertRaises to handle the Exception

    dictionaries/tests/test_dictionaries.py
    35    def test_making_a_dictionary_w_a_set_as_a_key(self):
    36        with self.assertRaises(TypeError):
    37            {{3, 2, 1}: 'BOOM!!!'}
    38
    39
    40# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_set_as_a_key'
    

I cannot use lists or sets as keys in a dictionary.


test_making_a_dictionary_w_a_dictionary_as_a_key

RED: make it fail


I add a test with a dictionary as a key in a dictionary

dictionaries/tests/test_dictionaries.py
36        with self.assertRaises(TypeError):
37            {[3, 2, 1]: 'BOOM!!!'}
38
39    def test_making_a_dictionary_w_a_dictionary_as_a_key(self):
40        a_dictionary = {'key': 'value'}
41        {a_dictionary: 'BOOM!!!'}
42
43
44# Exceptions seen

the terminal is my friend, and shows TypeError

terminal
TypeError: unhashable type: 'dict'

GREEN: make it pass


  • I add assertRaises

    dictionaries/tests/test_dictionaries.py
    39    def test_making_a_dictionary_w_a_dictionary_as_a_key(self):
    40        a_dictionary = {'key': 'value'}
    41        with self.assertRaises(TypeError):
    42            {a_dictionary: 'BOOM!!!'}
    43
    44
    45# Exceptions seen
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am \
    'add test_making_a_dictionary_w_a_dictionary_as_a_key'
    

I cannot use dictionaries, sets or lists as keys in a dictionary. They are not hashable, which means they can change in their lifetime.


test_dir_dict

RED: make it fail


I add a new test with the dir built-in function to see the attributes and methods of dictionaries

dictionaries/tests/test_dictionaries.py
41        with self.assertRaises(TypeError):
42            {a_dictionary: 'BOOM!!!'}
43
44    def test_dir_dict(self):
45        self.assertEqual(
46            dir(dict),
47            []
48        )
49
50
51# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: Lists differ: [
    '__class__', '__class_getitem__', '__cont[530 chars]ues'
] != []

It also gives me a message about how to show the full difference between the two lists

Diff is 720 characters long. Set self.maxDiff to None to see it.

GREEN: make it pass


  • I add maxDiff to the test_dir_dict

    dictionaries/tests/test_dictionaries.py
    44    def test_dir_dict(self):
    45        self.maxDiff = None
    46        self.assertEqual(
    47            dir(dict),
    48            []
    49        )
    

    the terminal is my friend, and shows the full difference between the two lists.

  • I copy (ctrl/command+c) and paste (ctrl/command+v) the expected values from the terminal then use find and replace to remove the extra characters

    Note

    results can be different because of the Python version.

    dictionaries/tests/test_dictionaries.py
    44    def test_dir_dict(self):
    45        self.maxDiff = None
    46        self.assertEqual(
    47            dir(dict),
    48            [
    49                '__class__',
    50                '__class_getitem__',
    51                '__contains__',
    52                '__delattr__',
    53                '__delitem__',
    54                '__dir__',
    55                '__doc__',
    56                '__eq__',
    57                '__format__',
    58                '__ge__',
    59                '__getattribute__',
    60                '__getitem__',
    61                '__getstate__',
    62                '__gt__',
    63                '__hash__',
    64                '__init__',
    65                '__init_subclass__',
    66                '__ior__',
    67                '__iter__',
    68                '__le__',
    69                '__len__',
    70                '__lt__',
    71                '__ne__',
    72                '__new__',
    73                '__or__',
    74                '__reduce__',
    75                '__reduce_ex__',
    76                '__repr__',
    77                '__reversed__',
    78                '__ror__',
    79                '__setattr__',
    80                '__setitem__',
    81                '__sizeof__',
    82                '__str__',
    83                '__subclasshook__',
    84                'clear',
    85                'copy',
    86                'fromkeys',
    87                'get',
    88                'items',
    89                'keys',
    90                'pop',
    91                'popitem',
    92                'setdefault',
    93                'update',
    94                'values'
    95            ]
    96        )
    

    the test passes.

  • I copy the names that do NOT have double underscores (__) and paste them below the test to make a TODO list that I use to test what I can do with dictionaries

    dictionaries/tests/test_dictionaries.py
     93                'update',
     94                'values'
     95            ]
     96        )
     97
     98
     99'clear',
    100'copy',
    101'fromkeys',
    102'get',
    103'items',
    104'keys',
    105'pop',
    106'popitem',
    107'setdefault',
    108'update',
    109'values'
    110
    111
    112# Exceptions seen
    

    the test is still green.


test_dir_dict with extend and sort

The attributes and methods of the dictionary object are the attributes and methods of ‘object’ with extra things. I can make the attributes and methods of the dictionary object by adding the “extra” to the attributes and methods of ‘object’, since they are both lists.


REFACTOR: make it better


I add a variable for the attributes and methods of the dict object, then add an assertion for it, in test_dir_dict

dictionaries/tests/test_dictionaries.py
44    def test_dir_dict(self):
45        self.maxDiff = None
46        dir_dict = dir(object)
47        dir_dict.extend((
48            'clear', 'copy', 'fromkeys',
49            'get', 'items', 'keys',
50            'pop', 'popitem', 'setdefault',
51            'update', 'values'
52        ))
53        self.assertEqual(
54            dir(dict),
55            dir_dict
56        )
57        self.assertEqual(
58            dir(dict),

the terminal is my friend, and shows AssertionError

terminal
AssertionError: Lists differ: [
    '__class__', '__class_getitem__', '__contains__',
    '__dela[514 chars]ues'
] != [
    '__class__', '__delattr__', '__dir__', '__doc__',
    '__eq__[361 chars]ues'
]

with a note about the difference

terminal
First list contains 11 additional elements.

GREEN: make it pass


  • I add the eleven additional elements

    dictionaries/tests/test_dictionaries.py
    47        dir_dict.extend((
    48            '__class_getitem__', '__contains__',
    49            '__delitem__', '__getitem__', '__ior__',
    50            '__iter__', '__len__', '__or__',
    51            '__reversed__', '__ror__', '__setitem__',
    52            'clear', 'copy', 'fromkeys',
    53            'get', 'items', 'keys',
    54            'pop', 'popitem', 'setdefault',
    55            'update', 'values'
    56        ))
    57        self.assertEqual(
    58            dir(dict),
    59            dir_dict
    60        )
    

    the terminal still shows AssertionError.

  • I add a call to the sort method

    dictionaries/tests/test_dictionaries.py
    47        dir_dict.extend((
    48            '__class_getitem__', '__contains__',
    49            '__delitem__', '__getitem__', '__ior__',
    50            '__iter__', '__len__', '__or__',
    51            '__reversed__', '__ror__', '__setitem__',
    52            'clear', 'copy', 'fromkeys',
    53            'get', 'items', 'keys',
    54            'pop', 'popitem', 'setdefault',
    55            'update', 'values'
    56        ))
    57        dir_dict.sort()
    58        self.assertEqual(
    59            dir(dict),
    60            dir_dict
    61        )
    62        self.assertEqual(
    63            dir(dict),
    

    the test passes because all objects inherit from ‘object’.


REFACTOR: make it better


  • I remove the other assertion from test_dir_dict

    dictionaries/tests/test_dictionaries.py
    58        self.assertEqual(
    59            dir(dict),
    60            dir_dict
    61        )
    62
    63
    64'clear',
    65'copy',
    66'fromkeys',
    67'get',
    68'items',
    69'keys',
    70'pop',
    71'popitem',
    72'setdefault',
    73'update',
    74'values'
    75
    76
    77# Exceptions seen
    
  • I add a git commit message

    terminal
    git commit -am 'add test_dir_dict'
    

All objects inherit attributes and methods from ‘object’.


test_clear_empties_a_dictionary

RED: make it fail


  • I add a test for the clear method

    dictionaries/tests/test_dictionaries.py
    58        self.assertEqual(
    59            dir(dict),
    60            dir_dict
    61        )
    62
    63    def test_clear(self):
    64        a_dictionary = {'key': 'value'}
    65        self.assertIsNone(a_dictionary.clear())
    66
    67
    68'clear',
    

    still green. The clear method returns None

  • I add an assertion to see what clear did to the dictionary

    dictionaries/tests/test_dictionaries.py
    63    def test_clear(self):
    64        a_dictionary = {'key': 'value'}
    65        self.assertIsNone(a_dictionary.clear())
    66        self.assertEqual(a_dictionary, {'key': 'value'})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {} != {'key': 'value'}
    

    the clear method emptied the dictionary, same as it does with lists.


GREEN: make it pass


I change the expectation to match

dictionaries/tests/test_dictionaries.py
63    def test_clear(self):
64        a_dictionary = {'key': 'value'}
65        self.assertIsNone(a_dictionary.clear())
66        self.assertEqual(a_dictionary, {})
67
68
69'clear',

the test passes.


REFACTOR: make it better


  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    58        self.assertEqual(
    59            dir(dict),
    60            dir_dict
    61        )
    62
    63    def test_clear_empties_a_dictionary(self):
    64        a_dictionary = {'key': 'value'}
    65        self.assertIsNone(a_dictionary.clear())
    66        self.assertEqual(a_dictionary, {})
    67
    68
    69'clear',
    
  • I remove clear from the TODO list

    dictionaries/tests/test_dictionaries.py
    66        self.assertEqual(a_dictionary, {})
    67
    68
    69'copy',
    70'fromkeys',
    71'get',
    72'items',
    73'keys',
    74'pop',
    75'popitem',
    76'setdefault',
    77'update',
    78'values'
    

I know how to empty a dictionary


test_copy_a_dictionary

RED: make it fail


I add a test for the copy method

dictionaries/tests/test_dictionaries.py
66        self.assertEqual(a_dictionary, {})
67
68    def test_copy(self):
69        a_dictionary = {'key': 'value'}
70        self.assertIsNone(a_dictionary.copy())
71
72
73'copy',
74'fromkeys',

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {'key': 'value'} is not None

this copy method returns a copy of the dictionary, same as with lists.


GREEN: make it pass


I add the value to the assertion

dictionaries/tests/test_dictionaries.py
68    def test_copy(self):
69        a_dictionary = {'key': 'value'}
70        self.assertIsNone(
71            a_dictionary.copy(),
72            {'key': 'value'}
73        )
74
75
76'copy',

the terminal is my friend, and shows AssertionError

terminal
AssertionError: {'key': 'value'}
                is not None : {'key': 'value'}

I change assertIsNone to assertEqual

dictionaries/tests/test_dictionaries.py
68    def test_copy(self):
69        a_dictionary = {'key': 'value'}
70        self.assertEqual(
71            a_dictionary.copy(),
72            {'key': 'value'}
73        )

the test passes.


REFACTOR: make it better


  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    66        self.assertEqual(a_dictionary, {})
    67
    68    def test_copy_a_dictionary(self):
    69        a_dictionary = {'key': 'value'}
    70        self.assertEqual(
    71            a_dictionary.copy(),
    72            {'key': 'value'}
    73        )
    74
    75
    76'copy',
    77'fromkeys',
    
  • I remove copy from the TODO list

    dictionaries/tests/test_dictionaries.py
    70        self.assertEqual(
    71            a_dictionary.copy(),
    72            {'key': 'value'}
    73        )
    74
    75
    76'fromkeys',
    77'get',
    78'items',
    79'keys',
    80'pop',
    81'popitem',
    82'setdefault',
    83'update',
    84'values'
    

I know how to copy a dictionary.


test_fromkeys_makes_a_dictionary_from_an_iterable

RED: make it fail


I add a test for the next method from the TODO list

dictionaries/tests/test_dictionaries.py
70        self.assertEqual(
71            a_dictionary.copy(),
72            {'key': 'value'}
73        )
74
75    def test_fromkeys(self):
76        a_dictionary = {'key': 'value'}
77        self.assertIsNone(a_dictionary.fromkeys())
78
79
80'fromkeys',

the terminal is my friend, and shows TypeError

terminal
TypeError: fromkeys expected at least 1 argument,
           got 0

GREEN: make it pass


  • I pass a value to the call

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertIsNone(a_dictionary.fromkeys(0))
    78
    79
    80'fromkeys',
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: 'int' object is not iterable
    
  • I change the value to a tuple

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertIsNone(
    78            a_dictionary.fromkeys((0, 1))
    79        )
    80
    81
    82'fromkeys',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {0: None, 1: None}
                    is not None
    

    the fromkeys method returns a dictionary that uses the values in the iterable as keys, and None as their default values. It reminds me of a list comprehension.

  • I add the dictionary as the expectation of the assertion

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertIsNone(
    78            a_dictionary.fromkeys((0, 1)),
    79            {0: None, 1: None}
    80        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {0: None, 1: None}
                    is not None : {0: None, 1: None}
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertEqual(
    78            a_dictionary.fromkeys((0, 1)),
    79            {0: None, 1: None}
    80        )
    81
    82
    83'fromkeys',
    

    the test passes.


REFACTOR: make it better


  • I add another assertion to see what happened to a_dictionary

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertEqual(
    78            a_dictionary.fromkeys((0, 1)),
    79            {0: None, 1: None}
    80        )
    81        self.assertEqual(a_dictionary, {})
    82
    83
    84'fromkeys',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value'} != {}
    

    the dictionary did not change

  • I remove self.assertEqual(a_dictionary, {})

  • I change a_dictionary.fromkeys((0, 1)) to use the dict class instead of a_dictionary

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        a_dictionary = {'key': 'value'}
    77        self.assertEqual(
    78            dict.fromkeys((0, 1)),
    79            {0: None, 1: None}
    80        )
    81
    82
    83'fromkeys',
    

    the test is still green.

  • I remove a_dictionary since it is no longer used

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        self.assertEqual(
    77            dict.fromkeys((0, 1)),
    78            {0: None, 1: None}
    79        )
    80
    81
    82'fromkeys',
    

    still green.

  • the dictionary made with the fromkeys method has None as the default values. When I called the method without inputs the terminal showed TypeError

    terminal
    TypeError: fromkeys expected at least 1 argument,
               got 0
    

    I add a second assertion to see what happens when I give None as the second input

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        self.assertEqual(
    77            dict.fromkeys((0, 1)),
    78            {0: None, 1: None}
    79        )
    80        self.assertEqual(
    81            dict.fromkeys((0, 1), None),
    82            {0: None, 1: None}
    83        )
    84
    85
    86'fromkeys',
    

    the test is still green.

  • I change the second input, I think this will fail

    dictionaries/tests/test_dictionaries.py
    75    def test_fromkeys(self):
    76        self.assertEqual(
    77            dict.fromkeys((0, 1)),
    78            {0: None, 1: None}
    79        )
    80        self.assertEqual(
    81            dict.fromkeys((0, 1), 'default'),
    82            {0: None, 1: None}
    83        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {0: 'default', 1: 'default'}
                 != {0: None, 1: None}
    
  • I change the values in the expectation to match

    dictionaries/tests/test_dictionaries.py
    80        self.assertEqual(
    81            dict.fromkeys((0, 1), 'default'),
    82            {0: 'default', 1: 'default'}
    83        )
    84
    85
    86'fromkeys',
    

    the test is green again.

  • This is like a dict comprehension because it made a dictionary using the items from an iterable as keys

    dictionaries/tests/test_dictionaries.py
    80        self.assertEqual(
    81            dict.fromkeys((0, 1), 'default'),
    82            {0: 'default', 1: 'default'}
    83        )
    84        self.assertEqual(
    85            {key: 'value' for key in (0, 1)},
    86            {}
    87        )
    88
    89
    90'fromkeys',
    

    the terminal is my friend, and shows AssertionError

    AssertionError: {0: 'value', 1: 'value'} != {}
    
  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    84        self.assertEqual(
    85            {key: 'value' for key in (0, 1)},
    86            {0: 'value', 1: 'value'}
    87        )
    88
    89
    90'fromkeys',
    

    the test passes.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    70        self.assertEqual(
    71            a_dictionary.copy(),
    72            {'key': 'value'}
    73        )
    74
    75    def test_fromkeys_makes_a_dictionary_from_an_iterable(self):
    76        self.assertEqual(
    77            dict.fromkeys((0, 1)),
    78            {0: None, 1: None}
    79        )
    
  • I remove fromkeys from the TODO list

    dictionaries/tests/test_dictionaries.py
    84        self.assertEqual(
    85            {key: 'value' for key in (0, 1)},
    86            {0: 'value', 1: 'value'}
    87        )
    88
    89
    90'get',
    91'items',
    92'keys',
    93'pop',
    94'popitem',
    95'setdefault',
    96'update',
    97'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_fromkeys_makes_a_dictionary_from_an_iterable'
    

I know how to make a dictionary from an iterable.


test_get_value_of_a_key_in_a_dictionary

RED: make it fail


I add a test for the get method

dictionaries/tests/test_dictionaries.py
84        self.assertEqual(
85            {key: 'value' for key in (0, 1)},
86            {0: 'value', 1: 'value'}
87        )
88
89    def test_get(self):
90        a_dictionary = {'key': 'value'}
91        self.assertIsNone(a_dictionary.get())
92
93
94'get',

the terminal is my friend, and shows TypeError

terminal
TypeError: get expected at least 1 argument,
           got 0

GREEN: make it pass


I add a value to the call

dictionaries/tests/test_dictionaries.py
89    def test_get(self):
90        a_dictionary = {'key': 'value'}
91        self.assertIsNone(a_dictionary.get(0))
92
93
94'get',

the test passes.


REFACTOR: make it better


  • the get method also expected at least one argument, I add another assertion with None as the second input to the call to the get method

    dictionaries/tests/test_dictionaries.py
    89    def test_get(self):
    90        a_dictionary = {'key': 'value'}
    91        self.assertIsNone(a_dictionary.get(0))
    92        self.assertIsNone(
    93            a_dictionary.get(0, None)
    94        )
    95
    96
    97'get',
    

    the test is still green.

  • I change the second argument, I think this will fail

    dictionaries/tests/test_dictionaries.py
    92        self.assertIsNone(
    93            a_dictionary.get(0, 'default'),
    94        )
    95
    96
    97'get',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None
    
  • I add the expectation

    dictionaries/tests/test_dictionaries.py
    92        self.assertIsNone(
    93            a_dictionary.get(0, 'default'),
    94            'default'
    95        )
    96
    97
    98'get',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None : default
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    89    def test_get(self):
    90        a_dictionary = {'key': 'value'}
    91        self.assertIsNone(a_dictionary.get(0))
    92        self.assertEqual(
    93            a_dictionary.get(0, 'default'),
    94            'default'
    95        )
    

    the test passes.

  • I change 0 in the call to make it clearer

    dictionaries/tests/test_dictionaries.py
     89    def test_get(self):
     90        a_dictionary = {'key': 'value'}
     91        self.assertIsNone(
     92            a_dictionary.get('not in dictionary')
     93        )
     94        self.assertEqual(
     95            a_dictionary.get(
     96                'not in dictionary', 'default'
     97            ),
     98            'default'
     99        )
    100
    101
    102'get',
    

    the test is still green.

  • I add another assertion to see what happens when I use the get method with a key that is in the dictionary

    dictionaries/tests/test_dictionaries.py
     94        self.assertEqual(
     95            a_dictionary.get(
     96                'not in dictionary', 'default'
     97            ),
     98            'default'
     99        )
    100        self.assertEqual(
    101            a_dictionary.get('key', 'default'),
    102            'default'
    103        )
    104
    105
    106'get',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'value' != 'default'
    

    I get 'value' back.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    100        self.assertEqual(
    101            a_dictionary.get('key', 'default'),
    102            'value'
    103        )
    104
    105
    106'get',
    

    the test passes. The get method has a condition

    a_dictionary = {'key': 'value'}
    
    • if the key is NOT in the dictionary, it returns the value of the default parameter

      a_dictionary.get('not in dictionary') -> None
      └── def get(self, key, default=None):
          ├── default = None
          ├── if key in self:
          │       return self[key]
          └── else:
              └── return default
      
      a_dictionary.get(
          'not in dictionary', 'default'
      ) -> 'default'
      └── def get(self, key, default=None):
          ├── default = 'default'
          ├── if key in self:
          │       return self[key]
          └── else:
              └── return default
      
    • if the key is in the dictionary, it returns its value

      a_dictionary.get(
          'key', 'default'
      ) -> 'value'
      └── def get(self, key, default=None):
          ├── default = 'default'
          └── if key in self:
              └── return self[key]
              else:
                  return default
      
  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    84        self.assertEqual(
    85            {key: 'value' for key in (0, 1)},
    86            {0: 'value', 1: 'value'}
    87        )
    88
    89    def test_get_value_of_a_key_in_a_dictionary(self):
    90        a_dictionary = {'key': 'value'}
    91        self.assertIsNone(
    92            a_dictionary.get('not in dictionary')
    93        )
    

    the test is still green.

  • I remove get from the TODO list

    dictionaries/tests/test_dictionaries.py
    100        self.assertEqual(
    101            a_dictionary.get('key', 'default'),
    102            'value'
    103        )
    104
    105
    106'items',
    107'keys',
    108'pop',
    109'popitem',
    110'setdefault',
    111'update',
    112'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_get_value_of_a_key_in_a_dictionary'
    

I know how to get the value of a key that is in a dictionary


test_items_returns_iterable_of_key_value_pairs_of_a_dictionary

RED: make it fail


I add the next test from the TODO list

dictionaries/tests/test_dictionaries.py
100        self.assertEqual(
101            a_dictionary.get('key', 'default'),
102            'value'
103        )
104
105    def test_items(self):
106        a_dictionary = {'key': 'value'}
107        self.assertIsNone(a_dictionary.items())
108
109
110'items',

the terminal is my friend, and shows AssertionError

terminal
AssertionError: dict_items([('key', 'value')])
                is not None

GREEN: make it pass


  • I copy the dict_items object from the terminal and paste it as the expectation

    dictionaries/tests/test_dictionaries.py
    105        a_dictionary = {'key': 'value'}
    106        self.assertIsNone(
    107            a_dictionary.items(),
    108            dict_items([('key', 'value')])
    109        )
    

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'dict_items' is not defined
    

    this new object has a list and I know how to work with lists.

  • I add NameError to the list of Exceptions seen

    dictionaries/tests/test_dictionaries.py
    122# Exceptions seen
    123# AssertionError
    124# TypeError
    125# NameError
    
  • I remove the stuff around the list

    dictionaries/tests/test_dictionaries.py
    107        self.assertIsNone(
    108            a_dictionary.items(),
    109            [('key', 'value')]
    110        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: dict_items([('key', 'value')])
                    is not None : [('key', 'value')]
    
  • I pass the call to the items method to list() to see if it is iterable

    dictionaries/tests/test_dictionaries.py
    107        self.assertIsNone(
    108            list(a_dictionary.items()),
    109            [('key', 'value')]
    110        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: [('key', 'value')]
                    is not None : [('key', 'value')]
    

    the values are the same.

  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    105    def test_items(self):
    106        a_dictionary = {'key': 'value'}
    107        self.assertEqual(
    108            list(a_dictionary.items()),
    109            [('key', 'value')]
    110        )
    

    the test passes.

This works because the items method returns an iterable of the key-value pairs of the dictionary. The dict_items object is iterable.


REFACTOR: make it better


  • I change the dictionary to see what the method does when there is more than one key-value pair

    dictionaries/tests/test_dictionaries.py
    105    def test_items(self):
    106        a_dictionary = {
    107            'key0': 'value0',
    108            'keyN': [0, 1, 2, 'n'],
    109        }
    110        self.assertEqual(
    111            list(a_dictionary.items()),
    112            [('key', 'value')]
    113        )
    114
    115
    116'items',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError:
        Lists differ: [('key0', 'value0'), ('keyN', [0, 1, 2, 'n'])]
                   != [('key', 'value')]
    
  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    110        self.assertEqual(
    111            list(a_dictionary.items()),
    112            [
    113                ('key0', 'value0'),
    114                ('keyN', [0, 1, 2, 'n']),
    115            ]
    116        )
    117
    118
    119'items',
    

    the test passes.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    100        self.assertEqual(
    101            a_dictionary.get('key', 'default'),
    102            'value'
    103        )
    104
    105    def test_items_returns_iterable_of_key_value_pairs_of_a_dictionary(self):
    106        a_dictionary = {
    107            'key0': 'value0',
    108            'keyN': [0, 1, 2, 'n'],
    109        }
    
  • I remove items from the TODO list

    dictionaries/tests/test_dictionaries.py
    110        self.assertEqual(
    111            list(a_dictionary.items()),
    112            [
    113                ('key0', 'value0'),
    114                ('keyN', [0, 1, 2, 'n']),
    115            ]
    116        )
    117
    118
    119'keys',
    120'pop',
    121'popitem',
    122'setdefault',
    123'update',
    124'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_items_returns_iterable_of_key_value_pairs_of_a_dictionary'
    

I know how to show the key-value pairs in a dictionary as a list of tuples.


test_keys_of_a_dictionary

RED: make it fail


I add a new test

dictionaries/tests/test_dictionaries.py
110            self.assertEqual(
111                list(a_dictionary.items()),
112                [
113                    ('key0', 'value0'),
114                    ('keyN', [0, 1, 2, 'n']),
115                ]
116            )
117
118    def test_keys(self):
119        a_dictionary = {'key': 'value'}
120        self.assertIsNone(a_dictionary.keys())
121
122
123'keys',

the terminal is my friend, and shows AssertionError

terminal
AssertionError: dict_keys(['key']) is not None

this looks like the error in test_items_returns_iterable_of_key_value_pairs_of_a_dictionary.


GREEN: make it pass


  • I copy the dict_keys object from the terminal and paste it as the expectation

    dictionaries/tests/test_dictionaries.py
    118    def test_keys(self):
    119        a_dictionary = {'key': 'value'}
    120        self.assertIsNone(
    121            a_dictionary.keys(),
    122            dict_keys(['key'])
    123        )
    124
    125
    126'keys',
    

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'dict_keys' is not defined
    

    the dict_keys object has a list.

  • I use the list in the dict_keys object as the expectation

    dictionaries/tests/test_dictionaries.py
    118    def test_keys(self):
    119        a_dictionary = {'key': 'value'}
    120        self.assertIsNone(
    121            a_dictionary.keys(),
    122            ['key']
    123        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: dict_keys(['key'])
                    is not None : ['key']
    
  • I pass the call to the keys method to list() to see if dict_keys is iterable

    dictionaries/tests/test_dictionaries.py
    118    def test_keys(self):
    119        a_dictionary = {'key': 'value'}
    120        self.assertIsNone(
    121            list(a_dictionary.keys()),
    122            ['key']
    123        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: ['key'] is not None : ['key']
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    118    def test_keys(self):
    119        a_dictionary = {'key': 'value'}
    120        self.assertEqual(
    121            list(a_dictionary.keys()),
    122            ['key']
    123        )
    

    the test passes.


REFACTOR: make it better


  • I change the dictionary to see what the keys method returns when there are multiple key-value pair

    dictionaries/tests/test_dictionaries.py
    118    def test_keys(self):
    119        a_dictionary = {
    120            'key0': 'value0',
    121            'keyN': [0, 1, 2, 'n'],
    122        }
    123        self.assertEqual(
    124            list(a_dictionary.keys()),
    125            ['key']
    126        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ:  ['key0', 'keyN'] != ['key']
    
  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    123        self.assertEqual(
    124            list(a_dictionary.keys()),
    125            ['key0', 'keyN']
    126        )
    127
    128
    129'keys',
    

    the test passes.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    110        self.assertEqual(
    111            list(a_dictionary.items()),
    112            [
    113                ('key0', 'value0'),
    114                ('keyN', [0, 1, 2, 'n']),
    115            ]
    116        )
    117
    118    def test_keys_of_a_dictionary(self):
    119        a_dictionary = {
    120            'key0': 'value0',
    121            'keyN': [0, 1, 2, 'n'],
    122        }
    
  • I remove keys from the TODO list

    dictionaries/tests/test_dictionaries.py
    123        self.assertEqual(
    124            list(a_dictionary.keys()),
    125            ['key0', 'keyN']
    126        )
    127
    128
    129'pop',
    130'popitem',
    131'setdefault',
    132'update',
    133'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_keys_of_a_dictionary'
    

I know how to look at the keys of a dictionary.


test_pop_removes_given_key_from_a_dictionary_and_returns_its_value

RED: make it fail


I wonder if the pop method of dictionaries behaves the same way as the pop method of lists. I add a test for it

dictionaries/tests/test_dictionaries.py
123        self.assertEqual(
124            list(a_dictionary.keys()),
125            ['key0', 'keyN']
126        )
127
128    def test_pop(self):
129        a_dictionary = {'key': 'value'}
130        self.assertIsNone(a_dictionary.pop())
131
132
133'pop',

the terminal is my friend, and shows TypeError

terminal
TypeError: pop expected at least 1 argument,
           got 0

this pop method is different from the pop method of lists.


GREEN: make it pass


  • I pass a value to the call

    dictionaries/tests/test_dictionaries.py
    128    def test_pop(self):
    129        a_dictionary = {'key': 'value'}
    130        self.assertIsNone(a_dictionary.pop(0))
    131
    132
    133'pop',
    

    the terminal is my friend, and shows KeyError

    terminal
    KeyError: 0
    
  • I add KeyError to the list of Exceptions seen

    dictionaries/tests/test_dictionaries.py
    140# Exceptions seen
    141# AssertionError
    142# TypeError
    143# NameError
    144# KeyError
    
  • I remove the things around the call in the test and change the value given to make it clearer

    dictionaries/tests/test_dictionaries.py
    128    def test_pop(self):
    129        a_dictionary = {'key': 'value'}
    130        a_dictionary.pop('not_in_dictionary')
    131
    132
    133'pop',
    

    the terminal is my friend, and shows KeyError

    terminal
    KeyError: 'not_in_dictionary'
    
  • I add assertRaises

    dictionaries/tests/test_dictionaries.py
    128    def test_pop(self):
    129        a_dictionary = {'key': 'value'}
    130
    131        with self.assertRaises(KeyError):
    132            a_dictionary.pop('not_in_dictionary')
    133
    134
    135'pop',
    

    the test passes. When I call the pop method with a key that is not in the dictionary it raises KeyError.


REFACTOR: make it better


  • When I called the pop method without input, the terminal showed TypeError

    terminal
    TypeError: pop expected at least 1 argument,
               got 0
    

    I add another assertion to see what happens when I call the pop method_ with two arguments

    dictionaries/tests/test_dictionaries.py
    131        with self.assertRaises(KeyError):
    132            a_dictionary.pop('not_in_dictionary')
    133
    134        self.assertIsNone(
    135            a_dictionary.pop('not_in_dictionary',  None)
    136        )
    137
    138
    139'pop',
    

    the test is still green.

  • I add another assertion with a different second argument, I think this will fail

    dictionaries/tests/test_dictionaries.py
    134        self.assertIsNone(
    135            a_dictionary.pop('not_in_dictionary',  None)
    136        )
    137        self.assertIsNone(
    138            a_dictionary.pop('not_in_dictionary', 'default')
    139        )
    140
    141
    142'pop',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None
    
  • I add the expectation

    dictionaries/tests/test_dictionaries.py
    137        self.assertIsNone(
    138            a_dictionary.pop('not_in_dictionary', 'default'),
    139            'default'
    140        )
    141
    142
    143'pop',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None : default
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    134        self.assertIsNone(
    135            a_dictionary.pop('not_in_dictionary',  None)
    136        )
    137        self.assertEqual(
    138            a_dictionary.pop('not_in_dictionary', 'default'),
    139            'default'
    140        )
    141
    142
    143'pop',
    

    the test passes.

  • I add another assertion to see what happens when I call the pop method with a key that is in the dictionary

    dictionaries/tests/test_dictionaries.py
    137        self.assertEqual(
    138            a_dictionary.pop('not_in_dictionary', 'default'),
    139            'default'
    140        )
    141        self.assertEqual(
    142            a_dictionary.pop('key', 'default'),
    143            'default'
    144        )
    145
    146
    147'pop',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'value' != 'default'
    

    I get 'value' back. The pop method returns the value of the given key from the dictionary.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    141        self.assertEqual(
    142            a_dictionary.pop('key', 'default'),
    143            'value'
    144        )
    145
    146
    147'pop',
    

    the test passes.

  • I add another assertion to see what the pop method did to the dictionary

    dictionaries/tests/test_dictionaries.py
    141        self.assertEqual(
    142            a_dictionary.pop('key', 'default'),
    143            'value'
    144        )
    145        self.assertEqual(a_dictionary, {'key': 'value'})
    146
    147
    148'pop',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {} != {'key': 'value'}
    

    the pop method removes the key-value pair and returns the value of the given key from the dictionary.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    141        self.assertEqual(
    142            a_dictionary.pop('key', 'default'),
    143            'value'
    144        )
    145        self.assertEqual(a_dictionary, {})
    146
    147
    148'pop',
    

    the test passes. The pop method has a condition with an Exception Handler

    a_dictionary = {'key': 'value'}
    
    • if the key is NOT in the dictionary, it raises KeyError if no value is given for the default parameter

      a_dictionary.pop('not_in_dictionary') -> KeyError
      └── def pop(self, key, default=something):
          ├── default = something
          └── try:
          ┌───┴── value = self[key]
          └── except KeyError:
              └── if default is something:
                  └── raise KeyError
                  return default
              else:
                  ...
      
    • if the key is NOT in the dictionary, it raises KeyError AND if a value is given for the default parameter

      a_dictionary.pop(
          'not_in_dictionary',  None
      ) -> None
      └── def pop(self, key, default=something):
          ├── default = None
          └── try:
          ┌───┴── value = self[key]
          └── except KeyError:
              ├── if default is something:
              │       raise KeyError
              └── return default
              else:
                  ...
      
      a_dictionary.pop(
          'not_in_dictionary', 'default'
      ) -> 'default'
      └── def pop(self, key, default=something):
          ├── default = 'default'
          └── try:
          ┌───┴── value = self[key]
          └── except KeyError:
              ├── if default is something:
              │       raise KeyError
              └── return default
              else:
                  ...
      
    • if the key is in the dictionary, it removes the key and returns its value

      a_dictionary.pop('key', 'default') -> 'value'
      └── def pop(self, key, default=something):
          ├── default = 'default'
          ├── try:
          │   └── value = self[key]
          │   except KeyError:
          │       if default is something:
          │           raise KeyError
          │       return default
          └── else:
              ├── del self[key]
              └── return value
      
  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    123        self.assertEqual(
    124            list(a_dictionary.keys()),
    125            ['key0', 'keyN']
    126        )
    127
    128    def test_pop_removes_given_key_from_a_dictionary_and_returns_its_value(self):
    129        a_dictionary = {'key': 'value'}
    
  • I remove pop from the TODO list

    dictionaries/tests/test_dictionaries.py
    145        self.assertEqual(a_dictionary, {})
    146
    147
    148'popitem',
    149'setdefault',
    150'update',
    151'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_pop_removes_given_key_from_a_dictionary_and_returns_its_value'
    

I know how to remove a key and its value from a dictionary


test_popitem_removes_and_returns_last_key_value_pair_from_a_dictionary

RED: make it fail


I add a failing test for the next item in the TODO list

dictionaries/tests/test_dictionaries.py
145        self.assertEqual(a_dictionary, {})
146
147    def test_popitem(self):
148        a_dictionary = {'key': 'value'}
149        self.assertIsNone(a_dictionary.popitem())
150
151
152'popitem',

the terminal is my friend, and shows AssertionError

terminal
AssertionError: ('key', 'value') is not None

the popitem method returns the key-value pair in the dictionary as a tuple.


GREEN: make it pass


  • I add the value from the terminal as the expectation

    dictionaries/tests/test_dictionaries.py
    147    def test_popitem(self):
    148        a_dictionary = {'key': 'value'}
    149        self.assertIsNone(
    150            a_dictionary.popitem(),
    151            ('key', 'value')
    152        )
    153
    154
    155'popitem',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: ('key', 'value')
                    is not None : ('key', 'value')
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    147    def test_popitem(self):
    148        a_dictionary = {'key': 'value'}
    149        self.assertEqual(
    150            a_dictionary.popitem(),
    151            ('key', 'value')
    152        )
    153
    154
    155'popitem',
    

    the test passes.


REFACTOR: make it better


  • I add another assertion to see what the popitem method did to the dictionary

    dictionaries/tests/test_dictionaries.py
    149        self.assertEqual(
    150            a_dictionary.popitem(),
    151            ('key', 'value')
    152        )
    153        self.assertEqual(a_dictionary, {'key': 'value'})
    154
    155
    156'popitem',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {} != {'key': 'value'}
    

    popitem removes and returns the key-value pair from the dictionary.

  • I change the value to match

    dictionaries/tests/test_dictionaries.py
    149        self.assertEqual(
    150            a_dictionary.popitem(),
    151            ('key', 'value')
    152        )
    153        self.assertEqual(a_dictionary, {})
    154
    155
    156'popitem',
    

    the test passes.

  • This operation does not take input, I change the dictionary to see what happens

    dictionaries/tests/test_dictionaries.py
    147    def test_popitem(self):
    148        a_dictionary = {
    149            'key0': 'value0',
    150            'keyN': [0, 1, 2, 'n'],
    151        }
    152        self.assertEqual(
    153            a_dictionary.popitem(),
    154            ('key', 'value')
    155        )
    156        self.assertEqual(a_dictionary, {})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Tuples differ: ('keyN', [0, 1, 2, 'n'])
                                != ('key', 'value')
    

    popitem removes and returns the last key-value pair from a dictionary.

  • I change the expectation of the first assertion

    dictionaries/tests/test_dictionaries.py
    152        self.assertEqual(
    153            a_dictionary.popitem(),
    154            ('keyN', [0, 1, 2, 'n'])
    155        )
    156        self.assertEqual(a_dictionary, {})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key0': 'value0'} != {}
    
  • I change the expectation of the second assertion

    dictionaries/tests/test_dictionaries.py
    152        self.assertEqual(
    153            a_dictionary.popitem(),
    154            ('keyN', [0, 1, 2, 'n'])
    155        )
    156        self.assertEqual(a_dictionary, {'key0': 'value0'})
    157
    158
    159'popitem',
    

    the test passes.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    145        self.assertEqual(a_dictionary, {})
    146
    147    def test_popitem_removes_and_returns_last_key_value_pair_from_a_dictionary(self):
    148        a_dictionary = {
    149            'key0': 'value0',
    150            'keyN': [0, 1, 2, 'n'],
    151        }
    
  • I remove popitem from the TODO list

    dictionaries/tests/test_dictionaries.py
    156        self.assertEqual(a_dictionary, {'key0': 'value0'})
    157
    158
    159'setdefault',
    160'update',
    161'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_popitem_removes_and_returns_last_key_value_pair_from_a_dictionary'
    

I know how to remove the last key-value pair from a dictionary.


test_setdefault_adds_given_key_to_a_dictionary

RED: make it fail


I add a test for the setdefault method

dictionaries/tests/test_dictionaries.py
156        self.assertEqual(a_dictionary, {'key0': 'value0'})
157
158    def test_setdefault(self):
159        a_dictionary = {'key': 'value'}
160        self.assertIsNone(a_dictionary.setdefault())
161
162
163'setdefault',

the terminal is my friend, and shows TypeError

terminal
TypeError: setdefault expected at least 1 argument,
           got 0

GREEN: make it pass


I pass a value in the call

dictionaries/tests/test_dictionaries.py
158    def test_setdefault(self):
159        a_dictionary = {'key': 'value'}
160        self.assertIsNone(a_dictionary.setdefault(0))
161
162
163'setdefault',

the test passes.


REFACTOR: make it better


  • The error message showed that the method expects at least one argument, I add a second argument

    dictionaries/tests/test_dictionaries.py
    158    def test_setdefault(self):
    159        a_dictionary = {'key': 'value'}
    160        self.assertIsNone(
    161            a_dictionary.setdefault(0, None)
    162        )
    163
    164
    165'setdefault',
    

    the test is still green.

  • I change the second argument, I think this will fail

    dictionaries/tests/test_dictionaries.py
    158    def test_setdefault(self):
    159        a_dictionary = {'key': 'value'}
    160        self.assertIsNone(
    161            a_dictionary.setdefault(0, 'default')
    162        )
    163
    164
    165'setdefault',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None
    
  • I add the expectation

    dictionaries/tests/test_dictionaries.py
    158    def test_setdefault(self):
    159        a_dictionary = {'key': 'value'}
    160        self.assertIsNone(
    161            a_dictionary.setdefault(0, 'default'),
    162            'default'
    163        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' is not None : default
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    158    def test_setdefault(self):
    159        a_dictionary = {'key': 'value'}
    160        self.assertEqual(
    161            a_dictionary.setdefault(0, 'default'),
    162            'default'
    163        )
    

    the test passes.

  • I add an assertion to see what setdefault did to the dictionary

    dictionaries/tests/test_dictionaries.py
    160        self.assertEqual(
    161            a_dictionary.setdefault(0, 'default'),
    162            'default'
    163        )
    164        self.assertEqual(a_dictionary, {'key': 'value'})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value', 0: 'default'} != {'key': 'value'}
    

    setdefault adds the given key to the dictionary with the default value and returns the default value.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    160        self.assertEqual(
    161            a_dictionary.setdefault(0, 'default'),
    162            'default'
    163        )
    164        self.assertEqual(
    165            a_dictionary,
    166            {
    167                'key': 'value',
    168                0: 'default',
    169            }
    170        )
    171
    172
    173'setdefault',
    

    the test passes.

  • I change the values given in the call to the setdefault method be clearer

    dictionaries/tests/test_dictionaries.py
    160        self.assertEqual(
    161            a_dictionary.setdefault('new_key', 'new value'),
    162            'default'
    163        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'new value' != 'default'
    
  • I change the expectation of the assertion

    dictionaries/tests/test_dictionaries.py
    160        self.assertEqual(
    161            a_dictionary.setdefault('new_key', 'new value'),
    162            'new value'
    163        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value', 'new_key': 'new value'}
                 != {'key': 'value', 0: 'default'}
    
  • I change the expectation of the second assertion to match

    dictionaries/tests/test_dictionaries.py
    164        self.assertEqual(
    165            a_dictionary,
    166            {
    167                'key': 'value',
    168                'new_key': 'new value',
    169            }
    170        )
    171
    172
    173'setdefault',
    

    the test is green again

  • I add an assertion to see what happens when I use setdefault with a key that is already in the dictionary

    dictionaries/tests/test_dictionaries.py
    158    def test_setdefault(self):
    159        a_dictionary = {'key': 'value'}
    160        self.assertEqual(
    161            a_dictionary.setdefault('new_key', 'new value'),
    162            'new value'
    163        )
    164        self.assertEqual(
    165            a_dictionary.setdefault('key', 'default'),
    166            'default'
    167        )
    168        self.assertEqual(
    169            a_dictionary,
    170            {
    171                'key': 'value',
    172                'new_key': 'new value',
    173            }
    174        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'value' != 'default'
    

    setdefault returns the value for a key in a dictionary, if the key is in the dictionary.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    164        self.assertEqual(
    165            a_dictionary.setdefault('key', 'default'),
    166            'value'
    167        )
    

    the test passes. The setdefault method has a condition

    a_dictionary = {'key': 'value'}
    
    • if the key is NOT in the dictionary, it adds it with the value of the value parameter and returns the value

      a_dictionary.setdefault('new_key') -> None
      └── def setdefault(self, key, value=None):
          ├── value = None
          └── if key not in self:
              ├── self[key] = value
              └── return value
              else:
                  ...
      
      a_dictionary.setdefault(
          'new_key', 'new value'
      ) -> 'new value'
      └── def setdefault(self, key, value=None):
          ├── value = 'new value'
          └── if key not in self:
              ├── self[key] = value
              └── return value
              else:
                  ...
      
    • if the key is in the dictionary it returns its value

      a_dictionary.setdefault('key', 'default') -> 'value'
      └── def setdefault(self, key, value=None):
          ├── value = 'default'
          ├── if key not in self:
          │       self[key] = value
          │       return value
          └── else:
                  return self[key]
      
  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    156        self.assertEqual(a_dictionary, {'key0': 'value0'})
    157
    158    def test_setdefault_adds_given_key_to_a_dictionary(self):
    159        a_dictionary = {'key': 'value'}
    
  • I remove setdefault from the TODO list

    dictionaries/tests/test_dictionaries.py
    168        self.assertEqual(
    169            a_dictionary,
    170            {
    171                'key': 'value',
    172                'new_key': 'new value',
    173            }
    174        )
    175
    176
    177'update',
    178'values'
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_setdefault_adds_given_key_to_a_dictionary'
    

I know how to add a key with a default value to a dictionary.


test_update_a_dictionary

RED: make it fail


  • I add a test for the next method from the TODO list

    dictionaries/tests/test_dictionaries.py
    168        self.assertEqual(
    169            a_dictionary,
    170            {
    171                'key': 'value',
    172                'new_key': 'new value',
    173            }
    174        )
    175
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178        self.assertIsNone(a_dictionary.update())
    179
    180
    181'update',
    

    the test is green. The update method returns None.

  • I add an assertion to see what it did to the dictionary

    dictionaries/tests/test_dictionaries.py
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178        self.assertIsNone(a_dictionary.update())
    179        self.assertEqual(a_dictionary, {})
    180
    181
    182'update',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value'} != {}
    

    the dictionary did not change.


GREEN: make it pass


I change the values in the expectation to match the terminal

dictionaries/tests/test_dictionaries.py
176    def test_update(self):
177        a_dictionary = {'key': 'value'}
178        self.assertIsNone(a_dictionary.update())
179        self.assertEqual(a_dictionary, {'key': 'value'})
180
181
182'update',

the test passes.


REFACTOR: make it better


  • I add a value to the call to the update method to see what happens

    dictionaries/tests/test_dictionaries.py
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178        self.assertIsNone(a_dictionary.update(0))
    179        self.assertEqual(a_dictionary, {'key': 'value'})
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: 'int' object is not iterable
    
  • I change the value to a tuple

    dictionaries/tests/test_dictionaries.py
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178        self.assertIsNone(a_dictionary.update((0, 1)))
    179        self.assertEqual(a_dictionary, {'key': 'value'})
    

    the terminal is my friend, and shows TypeError

    terminal
    TypeError: cannot convert dictionary update
               sequence element #0 to a sequence
    

    I had the same error message when I tried to make a dictionary with things in it.

  • I try a keyword argument

    dictionaries/tests/test_dictionaries.py
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178        self.assertIsNone(
    179            a_dictionary.update(new_key=[0, 1, 2, 'n'])
    180        )
    181        self.assertEqual(a_dictionary, {'key': 'value'})
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {'key': 'value', 'new_key': [0, 1, 2, 'n']}
                 != {'key': 'value'}
    
  • I add the new key-value pair to the expectation

    dictionaries/tests/test_dictionaries.py
    178        self.assertIsNone(
    179            a_dictionary.update(new_key=[0, 1, 2, 'n'])
    180        )
    181        self.assertEqual(
    182            a_dictionary,
    183            {
    184                'key': 'value',
    185                'new_key': [0, 1, 2, 'n'],
    186            }
    187        )
    188
    189
    190'update',
    

    the test passes.

  • I add an assertion to see what happens when I give a key that is already in the dictionary

    dictionaries/tests/test_dictionaries.py
    178        self.assertIsNone(
    179            a_dictionary.update(new_key=[0, 1, 2, 'n'])
    180        )
    181        self.assertIsNone(
    182            a_dictionary.update(key='updated value')
    183        )
    184        self.assertEqual(
    185            a_dictionary,
    186            {
    187                'key': 'value',
    188                'new_key': [0, 1, 2, 'n'],
    189            }
    190        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {
        'key': 'updated value',
        'new_key': [0, 1, 2, 'n']
    } != {'key': 'value', 'new_key': [0, 1, 2, 'n']}
    

    the update method changes the value for a key that is already in a dictionary.

  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    184        self.assertEqual(
    185            a_dictionary,
    186            {
    187                'key': 'updated value',
    188                'new_key': [0, 1, 2, 'n'],
    189            }
    190        )
    191
    192
    193'update',
    

    the test passes.

  • I add another assertion to show that the update method can also take a dictionary as input

    dictionaries/tests/test_dictionaries.py
    181        self.assertIsNone(
    182            a_dictionary.update(key='updated value')
    183        )
    184        self.assertIsNone(
    185            a_dictionary.update(
    186                {'another_key': {0, 1, 2, 'n'}}
    187            )
    188        )
    189        self.assertEqual(
    190            a_dictionary,
    191            {
    192                'key': 'updated value',
    193                'new_key': [0, 1, 2, 'n'],
    194            }
    195        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {
        'key[14 chars]lue',
        'new_key': [0, 1, 2, 'n'],
        'another_key': {0, 1, 2, 'n'}
    } != {'key[14 chars]lue', 'new_key': [0, 1, 2, 'n']}
    

    I can use the update method to add key-value pairs from one dictionary to another.

  • I change the expectation in the assertion to match

    dictionaries/tests/test_dictionaries.py
    189        self.assertEqual(
    190            a_dictionary,
    191            {
    192                'key': 'updated value',
    193                'new_key': [0, 1, 2, 'n'],
    194                'another_key': {0, 1, 2, 'n'},
    195            }
    196        )
    197
    198
    199'update',
    

    the test passes.

  • I add a for loop for the repeated calls to the update method

    dictionaries/tests/test_dictionaries.py
    184        self.assertIsNone(
    185            a_dictionary.update(
    186                {'another_key': {0, 1, 2, 'n'}}
    187            )
    188        )
    189        for key, value in (
    190            ('key', 'updated value'),
    191            ('new_key', [0, 1, 2, 'n']),
    192            ('another_key', {0, 1, 2, 'n'}),
    193        ):
    194            self.assertIsNone(
    195                a_dictionary.update(key=value)
    196            )
    197
    198        self.assertEqual(
    199            a_dictionary,
    200            {
    201                'key': 'updated value',
    202                'new_key': [0, 1, 2, 'n'],
    203                'another_key': {0, 1, 2, 'n'},
    204            }
    205        )
    206
    207
    208'update',
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: {
        'key': {0, 1, 2, 'n'},
        'new_key': [0, 1, 2, 'n'][27 chars]'n'}
    } != {
        'key': 'updated value',
        'new_key': [0, 1, 2, 'n'[28 chars]'n'}
    }
    

    it changed value for key because I used it as a keyword argument.

  • I change the input to the call to the update method to a dictionary

    dictionaries/tests/test_dictionaries.py
    194            self.assertIsNone(
    195                a_dictionary.update({key: value})
    196            )
    

    the test is green again.

  • I remove the first three assertions since they are now covered by the for loop

    dictionaries/tests/test_dictionaries.py
    176    def test_update(self):
    177        a_dictionary = {'key': 'value'}
    178
    179        for key, value in (
    180            ('key', 'updated value'),
    181            ('new_key', [0, 1, 2, 'n']),
    182            ('another_key', {0, 1, 2, 'n'}),
    183        ):
    184            self.assertIsNone(
    185                a_dictionary.update({key: value})
    186            )
    187
    188        self.assertEqual(
    189            a_dictionary,
    190            {
    191                'key': 'updated value',
    192                'new_key': [0, 1, 2, 'n'],
    193                'another_key': {0, 1, 2, 'n'},
    194            }
    195        )
    196
    197
    198'update',
    

    the test is still green.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    168        self.assertEqual(
    169            a_dictionary,
    170            {
    171                'key': 'value',
    172                'new_key': 'new value',
    173            }
    174        )
    175
    176    def test_update_a_dictionary(self):
    177        a_dictionary = {'key': 'value'}
    

    the test is still green.

  • I remove update from the TODO list

    dictionaries/tests/test_dictionaries.py
    188        self.assertEqual(
    189            a_dictionary,
    190            {
    191                'key': 'updated value',
    192                'new_key': [0, 1, 2, 'n'],
    193                'another_key': {0, 1, 2, 'n'},
    194            }
    195        )
    196
    197
    198'values'
    199
    200
    201# Exceptions seen
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_update_a_dictionary'
    

I know how to add key-value pairs from one dictionary to another.


test_values_of_a_dictionary

RED: make it fail


I add a test for the last method in my TODO list

dictionaries/tests/test_dictionaries.py
188        self.assertEqual(
189            a_dictionary,
190            {
191                'key': 'updated value',
192                'new_key': [0, 1, 2, 'n'],
193                'another_key': {0, 1, 2, 'n'},
194            }
195        )
196
197    def test_values(self):
198        a_dictionary = {'key': 'value'}
199        self.assertIsNone(a_dictionary.values())
200
201
202'values'

the terminal is my friend, and shows AssertionError

terminal
AssertionError: dict_values(['value']) is not None

this is like test_items_returns_iterable_of_key_value_pairs_of_a_dictionary and test_keys_of_a_dictionary.


GREEN: make it pass


  • I add the expected value

    dictionaries/tests/test_dictionaries.py
    197    def test_values(self):
    198        a_dictionary = {'key': 'value'}
    199        self.assertIsNone(
    200            a_dictionary.values(),
    201            dict_values(['value'])
    202        )
    203
    204
    205'values'
    

    the terminal is my friend, and shows NameError

    terminal
    NameError: name 'dict_values' is not defined
    
  • I remove the things around the list in the dict_values object

    dictionaries/tests/test_dictionaries.py
    199        self.assertIsNone(
    200            a_dictionary.values(),
    201            ['value']
    202        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: dict_values(['value'])
                    is not None : ['value']
    
  • I use list() to see if dict_values is iterable

    dictionaries/tests/test_dictionaries.py
    199        self.assertIsNone(
    200            list(a_dictionary.values()),
    201            ['value']
    202        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: ['value'] is not None : ['value']
    
  • I change assertIsNone to assertEqual

    dictionaries/tests/test_dictionaries.py
    197    def test_values(self):
    198        a_dictionary = {'key': 'value'}
    199        self.assertEqual(
    200            list(a_dictionary.values()),
    201            ['value']
    202        )
    

    the test passes.


REFACTOR: make it better


  • I change the dictionary to see what happens when it has more than one key-value pair

    dictionaries/tests/test_dictionaries.py
    197    def test_values(self):
    198        a_dictionary = {
    199            'key0': 'value0',
    200            'keyN': [0, 1, 2, 'n'],
    201        }
    202        self.assertEqual(
    203            list(a_dictionary.values()),
    204            ['value']
    205        )
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: Lists differ: ['value0', [0, 1, 2, 'n']]
                               != ['value']
    
  • I change the values in the expectation

    dictionaries/tests/test_dictionaries.py
    202        self.assertEqual(
    203            list(a_dictionary.values()),
    204            ['value0', [0, 1, 2, 'n']]
    205        )
    206
    207
    208'values'
    

    the test passes.

  • I change the name of the test

    dictionaries/tests/test_dictionaries.py
    188        self.assertEqual(
    189            a_dictionary,
    190            {
    191                'key': 'updated value',
    192                'new_key': [0, 1, 2, 'n'],
    193                'another_key': {0, 1, 2, 'n'},
    194            }
    195        )
    196
    197    def test_values_of_a_dictionary(self):
    198        a_dictionary = {
    199            'key0': 'value0',
    200            'keyN': [0, 1, 2, 'n'],
    201        }
    
  • I remove values from the TODO list

    dictionaries/tests/test_dictionaries.py
    202        self.assertEqual(
    203            list(a_dictionary.values()),
    204            ['value0', [0, 1, 2, 'n']]
    205        )
    206
    207
    208# Exceptions seen
    
  • I add a git commit message

    terminal
    git commit -am \
    'add test_values_of_a_dictionary'
    

I know how to look at the values of a dictionary.


test_key_error

KeyError is an important Exception to know when working with a dictionary. It happened earlier in my test for the pop method.


RED: make it fail


I add a test for getting the value of a key that is in a dictionary

dictionaries/tests/test_dictionaries.py
202        self.assertEqual(
203            list(a_dictionary.values()),
204            ['value0', [0, 1, 2, 'n']]
205        )
206
207    def test_key_error(self):
208        a_dictionary = {'key': 'value'}
209        self.assertEqual(
210            a_dictionary['key'], ''
211        )
212
213
214# Exceptions seen

the terminal is my friend, and shows AssertionError

terminal
AssertionError: 'value' != ''

I get 'value' back. I can get the value for a key in a dictionary by giving the key in [], the same way I can get items from a list by giving the index in [].


GREEN: make it pass


I change the value in the expectation to match the terminal

dictionaries/tests/test_dictionaries.py
207    def test_key_error(self):
208        a_dictionary = {'key': 'value'}
209        self.assertEqual(
210            a_dictionary['key'], 'value'
211        )
212
213
214# Exceptions seen

the test passes.


REFACTOR: make it better


  • I add another assertion, this time for a key that is not in the dictionary

    dictionaries/tests/test_dictionaries.py
    207    def test_key_error(self):
    208        a_dictionary = {'key': 'value'}
    209        self.assertEqual(
    210            a_dictionary['key'], 'value'
    211        )
    212        self.assertEqual(
    213            a_dictionary['not_in_dictionary']
    214        )
    215
    216
    217# Exceptions seen
    

    the terminal is my friend, and shows KeyError

    terminal
    KeyError: 'not_in_dictionary'
    
  • I change assertEqual to assertRaises

    dictionaries/tests/test_dictionaries.py
    209        self.assertEqual(
    210            a_dictionary['key'], 'value'
    211        )
    212
    213        with self.assertRaises(KeyError):
    214            a_dictionary['not_in_dictionary']
    215
    216
    217# Exceptions seen
    

    the test passes.

  • I can use the get method to avoid KeyError with a key that is not in a dictionary

    dictionaries/tests/test_dictionaries.py
    213        with self.assertRaises(KeyError):
    214            a_dictionary['not_in_dictionary']
    215        self.assertEqual(
    216            a_dictionary.get(
    217                'not_in_dictionary', 'default'
    218            ),
    219            ''
    220        )
    221
    222
    223# Exceptions seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' != ''
    
  • I change the expectation

    dictionaries/tests/test_dictionaries.py
    215        self.assertEqual(
    216            a_dictionary.get(
    217                'not_in_dictionary', 'default'
    218            ),
    219            'default'
    220        )
    221
    222
    223# Exceptions seen
    

    the test passes. I was wrong about the get method earlier, it uses an Exception handler like the pop method

    a_dictionary = {'key': 'value'}
    
    • if the key is NOT in the dictionary, it returns the value of the default parameter

      a_dictionary.get('not in dictionary') -> None
      └── def get(self, key, default=None):
          ├── default = None
          └── try:
          ┌───┴── return self[key]
          └── except KeyError:
              └── return default
      
      a_dictionary.get(
          'not in dictionary', 'default'
      ) -> 'default'
      └── def get(self, key, default=None):
          ├── default = 'default'
          └── try:
          ┌───┴── return self[key]
          └── except KeyError:
              └── return default
      
    • if the key is in the dictionary, it returns its value

      a_dictionary.get(
          'key', 'default'
      ) -> 'value'
      └── def get(self, key, default=None):
          ├── default = 'default'
          └── try:
              └── return self[key]
              except KeyError:
                  return default
      
  • The pop method raised KeyError when I gave it a key that was not in the dictionary, I add a failing line for it

    dictionaries/tests/test_dictionaries.py
    215        self.assertEqual(
    216            a_dictionary.get(
    217                'not_in_dictionary', 'default'
    218            ),
    219            'default'
    220        )
    221
    222        a_dictionary.pop('not_in_dictionary')
    223
    224
    225# Exceptions seen
    

    the terminal is my friend, and shows KeyError

    terminal
    KeyError: 'not_in_dictionary'
    
  • I add assertRaises

    dictionaries/tests/test_dictionaries.py
    215        self.assertEqual(
    216            a_dictionary.get(
    217                'not_in_dictionary', 'default'
    218            ),
    219            'default'
    220        )
    221
    222        with self.assertRaises(KeyError):
    223            a_dictionary.pop('not_in_dictionary')
    224
    225
    226# Exceptions seen
    

    the test passes.

  • I can give a second argument when I do not want the pop method to raise KeyError when the key is not in the dictionary. I add an assertion

    dictionaries/tests/test_dictionaries.py
    222        with self.assertRaises(KeyError):
    223            a_dictionary.pop('not_in_dictionary')
    224        self.assertEqual(
    225            a_dictionary.pop(
    226                'not_in_dictionary', 'default'
    227            ),
    228            ''
    229        )
    230
    231
    232# Exceptions seen
    

    the terminal is my friend, and shows AssertionError

    terminal
    AssertionError: 'default' != ''
    
  • I change the expectation to match

    dictionaries/tests/test_dictionaries.py
    224        self.assertEqual(
    225            a_dictionary.pop(
    226                'not_in_dictionary', 'default'
    227            ),
    228            'default'
    229        )
    

    the test passes.

  • The popitem method also raises KeyError when called on an empty dictionary

    dictionaries/tests/test_dictionaries.py
    224        self.assertEqual(
    225            a_dictionary.pop(
    226                'not_in_dictionary', 'default'
    227            ),
    228            'default'
    229        )
    230
    231        {}.popitem()
    232
    233
    234# Exceptions seen
    

    the terminal is my friend, and shows KeyError

    terminal
    KeyError: 'popitem(): dictionary is empty'
    

    I cannot remove the last key-value pair from a dictionary that has no key-value pairs.

  • I add assertRaises

    dictionaries/tests/test_dictionaries.py
    224        self.assertEqual(
    225            a_dictionary.pop(
    226                'not_in_dictionary', 'default'
    227            ),
    228            'default'
    229        )
    230
    231        with self.assertRaises(KeyError):
    232            {}.popitem()
    233
    234
    235# Exceptions seen
    236# AssertionError
    237# TypeError
    238# NameError
    239# KeyError
    

    the test passes.

  • I add a git commit message

    terminal
    git commit -am 'add test_key_error'
    

I know what causes KeyError.


close the project

  • I close test_dictionaries.py

  • I click in the terminal where the tests are running then use q on the keyboard to leave the tests

  • I change directory to the parent of dictionaries

    terminal
    cd ..
    

review

Dictionaries are also known as Mappings, they contain key-value pairs and any object can be used as values.

I ran tests to show that I can make a dictionary with dict() or curly braces {}, then I ran these tests to see what Python basic objects I can use as keys in a dictionary

I also ran these tests for the methods of dictionaries

and a test for the important Exception to know when working with dictionaries - KeyError


How many questions can you answer after going through this chapter?


code from the chapter

Do you want to see all the CODE I typed in this chapter?


what is next?

Would you like to use a dictionary in the ATM project?


rate pumping python

If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.


`