Lesson 3 ❮ Lesson List ❮ Top Page
❯ 3.3 Dictionaries
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳ Video 7m 19s
☷ Interactive readings 5m
Dictionaries are used to store data values in key : value pairs. They are written with curly brackes { } and have keys and values, separated by colon :.
To access the items of a dictionary, you can refer to its key name, inside square brackets.
get(key)
can also access the items by referring to key.
Generally, keys cannot be changed. You can change the values of a specific item by referring to its key name.
update(dict)
can also update the dictionary. The argument must be a dictionary.
Those two methods can also be used to add new keys:values pair into a dictionary.
Similar to the list,
pop()
removes the element with the specified key. The value of the removed item is the return value of the pop() method
In comparison to lists and tuples, dictionaries can get very lengthy. Writing them neatly helps with readability.
The closing brace/bracket/parenthesis on multiline constructs may either line up under the first non-whitespace character or the last line of list/dictionary (see example).
A KeyError is raised when a mapping key is accessed and is not found in the mapping.
You can use .get() to return either the value found at the specified key or a default value. It does not fix the problem but at least the error will not shows.
Change Line 6 using .get() instead of brackets [] to resolve the error in the code.