Skip to content

Commit 77a0810

Browse files
authored
[Edit/Update] Python - Collection-Module - defaultdict entry (#7621)
* Edit defaultdict.md to make it clear that default_factory in the syntax is a function * Correct from function to callable * Add examples of different callables being used * Revise writing * Test code and fix output * Further revision * Update defaultdict.md * Update defaultdict.md * Update content/python/concepts/collections-module/terms/defaultdict/defaultdict.md * Update content/python/concepts/collections-module/terms/defaultdict/defaultdict.md * Pushed minor changes ---------
1 parent 05e2e09 commit 77a0810

File tree

1 file changed

+67
-50
lines changed
  • content/python/concepts/collections-module/terms/defaultdict

1 file changed

+67
-50
lines changed
Lines changed: 67 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,115 +1,132 @@
11
---
22
Title: 'defaultdict'
3-
Description: 'Returns a dictionary-like object.'
3+
Description: 'Creates a dictionary-like object that provides default values for missing keys.'
44
Subjects:
55
- 'Computer Science'
66
- 'Data Science'
77
Tags:
8+
- 'Modules'
89
- 'Data Types'
910
- 'Dictionaries'
10-
- 'Modules'
11-
- 'Python'
1211
CatalogContent:
1312
- 'learn-python-3'
1413
- 'paths/computer-science'
1514
---
1615

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.
1817

19-
## Python `defaultdict` Syntax
18+
## Syntax
2019

2120
```pseudo
22-
from collections import defaultdict
23-
24-
defaultdict(default_factory)
21+
collections.defaultdict(default_factory)
2522
```
2623

2724
**Parameters:**
2825

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.
3327

3428
**Return value:**
3529

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`.
3731

38-
## Example 1: Counting Items Using Python `defaultdict`
32+
## Example 1: Using a Custom Function
3933

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:
4135

4236
```py
4337
from collections import defaultdict
4438

45-
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
39+
def default_value():
40+
return "Not Declared"
4641

47-
fruit_count = defaultdict(int)
42+
myDefaultDict = defaultdict(default_value)
4843

49-
for fruit in fruits:
50-
fruit_count[fruit] += 1
44+
myDefaultDict["first"] = 100
45+
myDefaultDict["second"] = 90
5146

52-
print(fruit_count)
47+
print(myDefaultDict["first"])
48+
print(myDefaultDict["second"])
49+
print(myDefaultDict["third"])
5350
```
5451

55-
Here is the output:
52+
Here is the output for the above code:
5653

5754
```shell
58-
defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'orange': 1})
55+
100
56+
90
57+
Not Declared
5958
```
6059

61-
## Example 2: Grouping Items Using Python `defaultdict`
60+
## Example 2: Using Built-in Callables
6261

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`:
6463

6564
```py
6665
from collections import defaultdict
6766

68-
names = [('Alice', 'Math'), ('Bob', 'Science'), ('Alice', 'English')]
67+
intDefaultDict = defaultdict(int)
68+
listDefaultDict = defaultdict(list)
69+
strDefaultDict = defaultdict(str)
70+
setDefaultDict = defaultdict(set)
6971

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'])
7676
```
7777

78-
Here is the output:
78+
Here is the output of the above code:
7979

8080
```shell
81-
defaultdict(<class 'list'>, {'Alice': ['Math', 'English'], 'Bob': ['Science']})
81+
0
82+
[]
83+
84+
set()
8285
```
8386

84-
## Codebyte Example: Using Custom Default Values in Python `defaultdict`
87+
## Example 3: Working with Lists
8588

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:
8790

88-
```codebyte/python
91+
```py
8992
from collections import defaultdict
9093

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.
9399

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+
```
95106

96-
ages['John'] = 25
97-
ages['Doe'] # Key doesn’t exist, uses default 18
107+
Here is the output of the above code:
98108

99-
print(ages)
109+
```shell
110+
[1]
111+
2
100112
```
101113

102-
## Frequently Asked Questions
114+
## Codebyte Example
103115

104-
### 1. What does `defaultdict` do in Python?
116+
Run the following codeblock and explore more about the `defaultdict` data type:
105117

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
107120
108-
### 2. Is `defaultdict` faster than `dict` in Python?
121+
def def_val():
122+
return "Unknown"
109123
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)
111125
112-
### 3. What is the difference between `get()` and `defaultdict` in Python?
126+
newDefaultDict["john"] = 25
127+
newDefaultDict["snow"] = 40
113128
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

Comments
 (0)