python collections defaultdict example
The main advantage of defaultdict is that it will not report an error when accessing non-existent keys, but will automatically generate default values. 1. Use defaultdict(int) to automatically initialize the value of the new key to 0, which is suitable for counting the number of elements; 2. Use defaultdict(list) to create an empty list for the new key, which is convenient for grouping data; 3. Use defaultdict(set) to automatically deduplicate, which is suitable for building graph structures; 4. You can pass in a custom callable object as the default factory, such as lambda or function, to achieve flexible initialization. Compared with ordinary dictionaries, it is necessary to manually determine whether the key exists or use the get method. The defaultdict is written more concise and efficient, especially in data grouping, counting and graph construction scenarios. However, it should be noted that it is not suitable for scenarios where precise control of key initialization or involves serialization. The final conclusion is that defaultdict is extremely practical in data processing and can significantly improve code readability.
defaultdict
is a very practical class in the Python collections
module. It inherits from dict
. The main advantage is that when accessing non-existent keys, there will be no errors, but a default type value will be automatically created . This is particularly convenient in handling grouping, counting and other scenarios.

The following is a few common examples to illustrate the usage of defaultdict
.
1. Use defaultdict
to count the number of elements to appear (replace dict.get()
)
from collections import defaultdict words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] # Use defaultdict to initialize the default value of each key to 0 word_count = defaultdict(int) for word in words: word_count[word] = 1 print(word_count) # Output: defaultdict(<class 'int'>, {'apple': 3, 'banana': 2, 'orange': 1})
✅ In
defaultdict(int)
int()
returns 0 by default, so the initial value of the key that does not appear is 0.
2. Use defaultdict(list)
to group data
from collections import defaultdict pairs = [('a', 1), ('b', 2), ('a', 3), ('b', 4), ('c', 5)] # Group according to the first element and collect the corresponding second element grouped = defaultdict(list) for key, value in pairs: grouped[key].append(value) print(grouped) # Output: defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2, 4], 'c': [5]})
✅
defaultdict(list)
will automatically create an empty list[]
for each new key, avoiding manual judgment on whether the key exists.
3. Use defaultdict(set)
to decompose and group
from collections import defaultdict edges = [('a', 1), ('b', 2), ('a', 1), ('a', 3), ('b', 2)] # Use set to avoid duplicate values graph = defaultdict(set) for node, neighbor in edges: graph[node].add(neighbor) print(graph) # Output: defaultdict(<class 'set'>, {'a': {1, 3}, 'b': {2}})
✅
set
can automatically deduplicate, which is suitable for constructing structures such as undirected graphs and adjacency tables.
4. Customize the default value (such as returning a default list or string)
from collections import defaultdict # Custom factory function def default_value(): return "not set" user_info = defaultdict(default_value) user_info['name'] = 'Alice' print(user_info['name']) # Output: Alice print(user_info['age']) # Output: Not set (no error report)
✅ You can pass in any "no parameter callable object" as the default factory, such as
lambda: 'unknown'
.
Summary: Commonly used defaultdict
types
type | default value | use |
---|---|---|
defaultdict(int) | 0 | Count, statistics |
defaultdict(list) | [] | Grouping, collecting |
defaultdict(set) | set() | Deduplication grouping |
defaultdict(str) | '' | String splicing (less used) |
defaultdict(lambda: 'default') | Customize | Flexible initialization |
Comparing the writing method of ordinary dictionaries (highlighting advantages)
# Ordinary dict writing (cumbersome) d = {} for word in words: if word not in d: d[word] = 0 d[word] = 1 # or use get d[word] = d.get(word, 0) 1 # defaultdict writing (concise) dd = defaultdict(int) for word in words: dd[word] = 1
✅
defaultdict
makes the code more concise and easy to read, reducing judgment logic.
Basically these common uses. defaultdict
is not omnipotent (for example, be careful when serializing), but it is very practical in data processing. If you use it too much, you will find that it is much refreshing than dict.setdefault()
or frequent judgment in
.
The above is the detailed content of python collections defaultdict example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

To get started with quantum machine learning (QML), the preferred tool is Python, and libraries such as PennyLane, Qiskit, TensorFlowQuantum or PyTorchQuantum need to be installed; then familiarize yourself with the process by running examples, such as using PennyLane to build a quantum neural network; then implement the model according to the steps of data set preparation, data encoding, building parametric quantum circuits, classic optimizer training, etc.; in actual combat, you should avoid pursuing complex models from the beginning, paying attention to hardware limitations, adopting hybrid model structures, and continuously referring to the latest documents and official documents to follow up on development.

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

In Python, the following points should be noted when merging strings using the join() method: 1. Use the str.join() method, the previous string is used as a linker when calling, and the iterable object in the brackets contains the string to be connected; 2. Make sure that the elements in the list are all strings, and if they contain non-string types, they need to be converted first; 3. When processing nested lists, you must flatten the structure before connecting.

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[

To master Python web crawlers, you need to grasp three core steps: 1. Use requests to initiate a request, obtain web page content through get method, pay attention to setting headers, handling exceptions, and complying with robots.txt; 2. Use BeautifulSoup or XPath to extract data. The former is suitable for simple parsing, while the latter is more flexible and suitable for complex structures; 3. Use Selenium to simulate browser operations for dynamic loading content. Although the speed is slow, it can cope with complex pages. You can also try to find a website API interface to improve efficiency.

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string
