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
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 )
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 )
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!!!'}
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 )
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 )
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 )
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 )
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 )
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 )
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, {})
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'})
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 )
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 )
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 )
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
dictionariesas the first argument to the makePythonTdd programthe terminal is my friend, and shows AssertionError
======================== 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.pyfrom thetestsfolder then put the cursor on line 7I change assertFalse to assertTrue
4class Testdictionaries(unittest.TestCase): 5 6 def test_failure(self): 7 # self.assertFalse(True) 8 self.assertTrue(True) 9 10 11# Exceptions seenthe test passes.
I change
TestdictionariestoTestDictionariesto match Python conventionI open a new terminal then change directory to
dictionariesI add a git commit message
test_making_a_dictionary
RED: make it fail
I change test_failure to test_making_a_dictionary then add an assertion
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
GREEN: make it pass
I change the expectation to match
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
6 def test_making_a_dictionary(self): 7 self.assertEqual(dict(), {}) 8 self.assertEqual(dict(0), {}) 9 10 11# Exceptions seenI add TypeError to the list of Exceptions seen
I change the value given to
dict()to a tuple7 self.assertEqual(dict(), {}) 8 self.assertEqual(dict((0, 1)), {}) 9 10 11# Exceptions seenthe terminal is my friend, and shows TypeError
TypeError: cannot convert dictionary update sequence element #0 to a sequenceI try a keyword argument
7 self.assertEqual(dict(), {}) 8 self.assertEqual(dict(key='value'), {})the terminal is my friend, and shows AssertionError
I change the expectation to match the values in the terminal
6 def test_making_a_dictionary(self): 7 self.assertEqual(dict(), {}) 8 self.assertEqual(dict(key='value'), {'key': 'value'}) 9 10 11# Exceptions seenthe test passes.
I add a git commit message
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
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
GREEN: make it pass
I change
'bap'to'boom'10 def test_making_a_dictionary_w_none_as_a_key(self): 11 self.assertEqual({None: 'boom'}, {None: 'boom'}) 12 13 14# Exceptions seenthe test passes.
I add a git commit message
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
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
GREEN: make it pass
I change
'bap'to'boom'13 def test_making_a_dictionary_w_a_boolean_as_a_key(self): 14 self.assertEqual({False: 'boom'}, {False: 'boom'}) 15 16 17# Exceptions seenthe test passes.
I can use False as a key in a dictionary
REFACTOR: make it better
I add an assertion for the other boolean
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
I add the new key-value pair to the expectation
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 seenthe test passes.
I add a git commit message
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
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
GREEN: make it pass
I change 'bap' to 'boom'
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
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
I add the new key-value pair to the expectation
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
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
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
GREEN: make it pass
I change
'bap'to'boom'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 seenthe test passes.
I add a git commit message
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
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
GREEN: make it pass
I remove the things around the new dictionary then change the key and value for fun
31 def test_making_a_dictionary_w_a_list_as_a_key(self): 32 33 {[3, 2, 1]: 'BOOM!!!'} 34 35 36# Exceptions seenI add assertRaises
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
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
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
GREEN: make it pass
I add assertRaises to handle the Exception
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 seenthe test passes.
I add a git commit message
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
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
GREEN: make it pass
I add assertRaises
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 seenthe test passes.
I add a git commit message
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
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
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
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.
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 dictionaries93 '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 seenthe 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
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
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
GREEN: make it pass
I add the eleven additional elements
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
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
I add a git commit message
test_clear_empties_a_dictionary
RED: make it fail
I add a test for the clear method
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
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
the clear method emptied the dictionary, same as it does with lists.
GREEN: make it pass
I change the expectation to match
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
I remove clear from the TODO list
test_copy_a_dictionary
RED: make it fail
I add a test for the copy method
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
this copy method returns a copy of the dictionary, same as with lists.
GREEN: make it pass
I add the value to the assertion
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
I change assertIsNone to assertEqual
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
I remove copy from the TODO list
test_fromkeys_makes_a_dictionary_from_an_iterable
RED: make it fail
I add a test for the next method from the TODO list
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',
GREEN: make it pass
I pass a value to the call
75 def test_fromkeys(self): 76 a_dictionary = {'key': 'value'} 77 self.assertIsNone(a_dictionary.fromkeys(0)) 78 79 80'fromkeys',I change the value to a tuple
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
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
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
I change assertIsNone to assertEqual
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_dictionary75 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
the dictionary did not change
I remove
self.assertEqual(a_dictionary, {})I change
a_dictionary.fromkeys((0, 1))to use the dict class instead ofa_dictionary75 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_dictionarysince it is no longer used75 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
I add a second assertion to see what happens when I give None as the second input
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
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
I change the values in the expectation to match
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
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
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
I remove fromkeys from the TODO list
I add a git commit message
test_get_value_of_a_key_in_a_dictionary
RED: make it fail
I add a test for the get method
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',
GREEN: make it pass
I add a value to the call
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
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
92 self.assertIsNone( 93 a_dictionary.get(0, 'default'), 94 ) 95 96 97'get',the terminal is my friend, and shows AssertionError
I add the expectation
92 self.assertIsNone( 93 a_dictionary.get(0, 'default'), 94 'default' 95 ) 96 97 98'get',the terminal is my friend, and shows AssertionError
I change assertIsNone to assertEqual
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
0in the call to make it clearer89 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
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
I get
'value'back.I change the expectation to match
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
defaultparametera_dictionary.get('not in dictionary') -> None └── def get(self, key, default=None): ├── default = None ├── if key in self: │ return self[key] └── else: └── return defaulta_dictionary.get( 'not in dictionary', 'default' ) -> 'default' └── def get(self, key, default=None): ├── default = 'default' ├── if key in self: │ return self[key] └── else: └── return defaultif 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
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
I add a git commit message
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
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
GREEN: make it pass
I copy the
dict_itemsobject from the terminal and paste it as the expectation105 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
this new object has a list and I know how to work with lists.
I add NameError to the list of Exceptions seen
I remove the stuff around the list
107 self.assertIsNone( 108 a_dictionary.items(), 109 [('key', 'value')] 110 )the terminal is my friend, and shows AssertionError
I pass the call to the items method to
list()to see if it is iterable107 self.assertIsNone( 108 list(a_dictionary.items()), 109 [('key', 'value')] 110 )the terminal is my friend, and shows AssertionError
the values are the same.
I change assertIsNone to assertEqual
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
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
I change the expectation to match
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
I remove items from the TODO list
I add a git commit message
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
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
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_keysobject from the terminal and paste it as the expectation118 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',I use the list in the
dict_keysobject as the expectation118 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
I pass the call to the keys method to
list()to see ifdict_keysis iterable118 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
I change assertIsNone to assertEqual
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
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
I change the expectation to match
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
I remove keys from the TODO list
I add a git commit message
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
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
this pop method is different from the pop method of lists.
GREEN: make it pass
I pass a value to the call
128 def test_pop(self): 129 a_dictionary = {'key': 'value'} 130 self.assertIsNone(a_dictionary.pop(0)) 131 132 133'pop',I add KeyError to the list of Exceptions seen
I remove the things around the call in the test and change the value given to make it clearer
128 def test_pop(self): 129 a_dictionary = {'key': 'value'} 130 a_dictionary.pop('not_in_dictionary') 131 132 133'pop',I add assertRaises
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
I add another assertion to see what happens when I call the pop method_ with two arguments
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
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
I add the expectation
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
I change assertIsNone to assertEqual
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
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
I get
'value'back. The pop method returns the value of the given key from the dictionary.I change the expectation to match
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
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
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
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
defaultparametera_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
defaultparametera_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
I remove pop from the TODO list
I add a git commit message
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
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
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
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
I change assertIsNone to assertEqual
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
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
popitem removes and returns the key-value pair from the dictionary.
I change the value to match
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
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
popitem removes and returns the last key-value pair from a dictionary.
I change the expectation of the first assertion
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
I change the expectation of the second assertion
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
I remove popitem from the TODO list
I add a git commit message
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
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',
GREEN: make it pass
I pass a value in the call
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
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
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
I add the expectation
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
I change assertIsNone to assertEqual
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
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
setdefault adds the given key to the dictionary with the default value and returns the default value.
I change the expectation to match
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
160 self.assertEqual( 161 a_dictionary.setdefault('new_key', 'new value'), 162 'default' 163 )the terminal is my friend, and shows AssertionError
I change the expectation of the assertion
160 self.assertEqual( 161 a_dictionary.setdefault('new_key', 'new value'), 162 'new value' 163 )the terminal is my friend, and shows AssertionError
I change the expectation of the second assertion to match
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
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
setdefault returns the value for a key in a dictionary, if the key is in the dictionary.
I change the expectation to match
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
valueparameter and returns the valuea_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
I remove setdefault from the TODO list
I add a git commit message
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
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
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
the dictionary did not change.
GREEN: make it pass
I change the values in the expectation to match the terminal
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
176 def test_update(self): 177 a_dictionary = {'key': 'value'} 178 self.assertIsNone(a_dictionary.update(0)) 179 self.assertEqual(a_dictionary, {'key': 'value'})I change the value to a tuple
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
I had the same error message when I tried to make a dictionary with things in it.
I try a keyword argument
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
I add the new key-value pair to the expectation
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
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
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
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
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
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
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
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
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
keybecause I used it as a keyword argument.I change the input to the call to the update method to a dictionary
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
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
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
I add a git commit message
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
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
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
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'I remove the things around the list in the
dict_valuesobject199 self.assertIsNone( 200 a_dictionary.values(), 201 ['value'] 202 )the terminal is my friend, and shows AssertionError
I use
list()to see ifdict_valuesis iterable199 self.assertIsNone( 200 list(a_dictionary.values()), 201 ['value'] 202 )the terminal is my friend, and shows AssertionError
I change assertIsNone to assertEqual
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
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
I change the values in the expectation
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
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
valuesfrom the TODO listI add a git commit message
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
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
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
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
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 seenI change assertEqual to assertRaises
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 seenthe test passes.
I can use the get method to avoid KeyError with a key that is not in a dictionary
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 seenthe terminal is my friend, and shows AssertionError
I change the expectation
215 self.assertEqual( 216 a_dictionary.get( 217 'not_in_dictionary', 'default' 218 ), 219 'default' 220 ) 221 222 223# Exceptions seenthe 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
defaultparametera_dictionary.get('not in dictionary') -> None └── def get(self, key, default=None): ├── default = None └── try: ┌───┴── return self[key] └── except KeyError: └── return defaulta_dictionary.get( 'not in dictionary', 'default' ) -> 'default' └── def get(self, key, default=None): ├── default = 'default' └── try: ┌───┴── return self[key] └── except KeyError: └── return defaultif 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
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 seenI add assertRaises
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 seenthe 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
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 seenthe terminal is my friend, and shows AssertionError
I change the expectation to match
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
224 self.assertEqual( 225 a_dictionary.pop( 226 'not_in_dictionary', 'default' 227 ), 228 'default' 229 ) 230 231 {}.popitem() 232 233 234# Exceptions seenthe terminal is my friend, and shows KeyError
I cannot remove the last key-value pair from a dictionary that has no key-value pairs.
I add assertRaises
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# KeyErrorthe test passes.
I add a git commit message
close the project
I close
test_dictionaries.pyI 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
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
test_items_returns_iterable_of_key_value_pairs_of_a_dictionary
test_pop_removes_given_key_from_a_dictionary_and_returns_its_value
test_popitem_removes_and_returns_last_key_value_pair_from_a_dictionary
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
what is next?
I know how to make a Python Test Driven Development environment manually.
I know how to make a Python Test Driven Development environment automatically.
I know how to make a Python Test Driven Development environment automatically with variables.
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.
`