In this lesson, you’ll learn about dictionaries and collections.defaultdict
. Dictionaries are a data structure that allows you to store key-value pairs. It allows inserting and retrieving key-value pairs in constant time. collections.defaultdict
is a subclass of the dictionary data structure that allows for default values if the key does not exist in the dictionary:
>>> student_grades = {"Jack": [85, 90], "Jill": [80, 95]}
>>> student_grades["Jack"]
[85, 90]
>>> student_grades.get("Joe", [])
[]
>>> student_grades["Joe"]
KeyError: 'Joe'
>>> student_grades.setdefault("Joe", [])
[]
>>> student_grades["Joe"]
[]
>>> from collections import defaultdict
>>> d = defaultdict(lambda: 10)
>>> d[5]
10
>>> d[5] += 10
>>> d[5]
20
If you want to learn more, check out Dictionaries in Python and Using the Python defaultdict Type for Handling Missing Keys.
Pygator on April 30, 2020
So all of that is using VS code editor? It looks like a darker jupyter-nb on the side.