|
1 | 1 | --- |
2 | 2 | Title: 'defaultdict' |
3 | | -Description: 'Returns a dictionary-like object.' |
| 3 | +Description: 'Creates a dictionary-like object that provides default values for missing keys.' |
4 | 4 | Subjects: |
5 | 5 | - 'Computer Science' |
6 | 6 | - 'Data Science' |
7 | 7 | Tags: |
| 8 | + - 'Modules' |
8 | 9 | - 'Data Types' |
9 | 10 | - 'Dictionaries' |
10 | | - - 'Modules' |
11 | | - - 'Python' |
12 | 11 | CatalogContent: |
13 | 12 | - 'learn-python-3' |
14 | 13 | - 'paths/computer-science' |
15 | 14 | --- |
16 | 15 |
|
17 | | -Python **`defaultdict`** is a [data type](https://www.codecademy.com/resources/docs/python/data-types) that belongs to the `collections` [module](https://www.codecademy.com/resources/docs/python/modules). It is a [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries) subclass that is used to return a dictionary-like object. |
| 16 | +In Python, **`defaultdict`** is a data type that belongs to the [`collections`](https://www.codecademy.com/resources/docs/python/collections-module) module. It is a [dictionary](https://www.codecademy.com/resources/docs/python/dictionaries) subclass that automatically provides a default value for missing keys. |
18 | 17 |
|
19 | | -## Python `defaultdict` Syntax |
| 18 | +## Syntax |
20 | 19 |
|
21 | 20 | ```pseudo |
22 | | -from collections import defaultdict |
23 | | -
|
24 | | -defaultdict(default_factory) |
| 21 | +collections.defaultdict(default_factory) |
25 | 22 | ``` |
26 | 23 |
|
27 | 24 | **Parameters:** |
28 | 25 |
|
29 | | -- `default_factory`: A [function](https://www.codecademy.com/resources/docs/python/functions) that provides the default value for nonexistent keys. Commonly used with int, list, set, or even custom functions. Examples include: |
30 | | - - `int()`: Default value is `0`. |
31 | | - - `list()`:Default value is `[]`. |
32 | | - - `set()`: Default value is `set()`. |
| 26 | +- `default_factory`: A callable (such as a function or type like `int`, `list`, `set`) that provides the default value for missing keys. If set to `None`, a `KeyError` is raised when accessing a missing key. |
33 | 27 |
|
34 | 28 | **Return value:** |
35 | 29 |
|
36 | | -Returns a `defaultdict` object. If a key does not exist, accessing it will automatically create it with the value returned by `default_factory`. |
| 30 | +Returns a `defaultdict` object, which behaves like a dictionary but creates default values for missing keys using the specified `default_factory`. |
37 | 31 |
|
38 | | -## Example 1: Counting Items Using Python `defaultdict` |
| 32 | +## Example 1: Using a Custom Function |
39 | 33 |
|
40 | | -This example uses Python `defaultdict` to count the frequency of elements in a list: |
| 34 | +The following example demonstrates the `defaultdict` data type with a custom function as `default_factory` argument: |
41 | 35 |
|
42 | 36 | ```py |
43 | 37 | from collections import defaultdict |
44 | 38 |
|
45 | | -fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] |
| 39 | +def default_value(): |
| 40 | + return "Not Declared" |
46 | 41 |
|
47 | | -fruit_count = defaultdict(int) |
| 42 | +myDefaultDict = defaultdict(default_value) |
48 | 43 |
|
49 | | -for fruit in fruits: |
50 | | - fruit_count[fruit] += 1 |
| 44 | +myDefaultDict["first"] = 100 |
| 45 | +myDefaultDict["second"] = 90 |
51 | 46 |
|
52 | | -print(fruit_count) |
| 47 | +print(myDefaultDict["first"]) |
| 48 | +print(myDefaultDict["second"]) |
| 49 | +print(myDefaultDict["third"]) |
53 | 50 | ``` |
54 | 51 |
|
55 | | -Here is the output: |
| 52 | +Here is the output for the above code: |
56 | 53 |
|
57 | 54 | ```shell |
58 | | -defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'orange': 1}) |
| 55 | +100 |
| 56 | +90 |
| 57 | +Not Declared |
59 | 58 | ``` |
60 | 59 |
|
61 | | -## Example 2: Grouping Items Using Python `defaultdict` |
| 60 | +## Example 2: Using Built-in Callables |
62 | 61 |
|
63 | | -Python `defaultdict` can group items easily without checking if the key exists: |
| 62 | +This example demonstrates `defaultdict` with built-in types (`int`, `list`, `str`, `set`) as the `default_factory`: |
64 | 63 |
|
65 | 64 | ```py |
66 | 65 | from collections import defaultdict |
67 | 66 |
|
68 | | -names = [('Alice', 'Math'), ('Bob', 'Science'), ('Alice', 'English')] |
| 67 | +intDefaultDict = defaultdict(int) |
| 68 | +listDefaultDict = defaultdict(list) |
| 69 | +strDefaultDict = defaultdict(str) |
| 70 | +setDefaultDict = defaultdict(set) |
69 | 71 |
|
70 | | -grouped = defaultdict(list) |
71 | | - |
72 | | -for name, subject in names: |
73 | | - grouped[name].append(subject) |
74 | | - |
75 | | -print(grouped) |
| 72 | +print(intDefaultDict[0]) |
| 73 | +print(listDefaultDict['zero']) |
| 74 | +print(strDefaultDict['0']) |
| 75 | +print(setDefaultDict['a']) |
76 | 76 | ``` |
77 | 77 |
|
78 | | -Here is the output: |
| 78 | +Here is the output of the above code: |
79 | 79 |
|
80 | 80 | ```shell |
81 | | -defaultdict(<class 'list'>, {'Alice': ['Math', 'English'], 'Bob': ['Science']}) |
| 81 | +0 |
| 82 | +[] |
| 83 | + |
| 84 | +set() |
82 | 85 | ``` |
83 | 86 |
|
84 | | -## Codebyte Example: Using Custom Default Values in Python `defaultdict` |
| 87 | +## Example 3: Working with Lists |
85 | 88 |
|
86 | | -This codebyte example provides a custom default value to Python `defaultdict`: |
| 89 | +This example shows how `list` as `default_factory` allows appending to keys that don’t yet exist: |
87 | 90 |
|
88 | | -```codebyte/python |
| 91 | +```py |
89 | 92 | from collections import defaultdict |
90 | 93 |
|
91 | | -def default_age(): |
92 | | - return 18 |
| 94 | +myDefaultDict = defaultdict(list) |
| 95 | + |
| 96 | +myDefaultDict['apple'].append(1) |
| 97 | +# myDefaultDict['apple'] does not exist so it defaults to empty list [], |
| 98 | +# then 1 is appended to it. |
93 | 99 |
|
94 | | -ages = defaultdict(default_age) |
| 100 | +myDefaultDict['orange'] = 2 |
| 101 | +#The empty list [] is replaced by integer 2 here. |
| 102 | + |
| 103 | +print(myDefaultDict['apple']) |
| 104 | +print(myDefaultDict['orange']) |
| 105 | +``` |
95 | 106 |
|
96 | | -ages['John'] = 25 |
97 | | -ages['Doe'] # Key doesn’t exist, uses default 18 |
| 107 | +Here is the output of the above code: |
98 | 108 |
|
99 | | -print(ages) |
| 109 | +```shell |
| 110 | +[1] |
| 111 | +2 |
100 | 112 | ``` |
101 | 113 |
|
102 | | -## Frequently Asked Questions |
| 114 | +## Codebyte Example |
103 | 115 |
|
104 | | -### 1. What does `defaultdict` do in Python? |
| 116 | +Run the following codeblock and explore more about the `defaultdict` data type: |
105 | 117 |
|
106 | | -Python `defaultdict` automatically assigns a default value to keys that do not exist, preventing KeyError and reducing the need for explicit key checks. |
| 118 | +```codebyte/python |
| 119 | +from collections import defaultdict |
107 | 120 |
|
108 | | -### 2. Is `defaultdict` faster than `dict` in Python? |
| 121 | +def def_val(): |
| 122 | + return "Unknown" |
109 | 123 |
|
110 | | -In Python, `defaultdict` can be faster than `dict` in scenarios where missing keys are frequently accessed or initialized, as it avoids repeated conditional checks. |
| 124 | +newDefaultDict = defaultdict(def_val) |
111 | 125 |
|
112 | | -### 3. What is the difference between `get()` and `defaultdict` in Python? |
| 126 | +newDefaultDict["john"] = 25 |
| 127 | +newDefaultDict["snow"] = 40 |
113 | 128 |
|
114 | | -- `dict.get(key, default)`: Returns the value for `key` if it exists; otherwise, returns the specified `default` without modifying the dictionary. |
115 | | -- `defaultdict`: Automatically inserts the key with a default value (from `default_factory`) into the dictionary when accessed. |
| 129 | +print(newDefaultDict["john"]) |
| 130 | +print(newDefaultDict["snow"]) |
| 131 | +print(newDefaultDict["smith"]) |
| 132 | +``` |
0 commit comments