Contents
- Abstract:
- Original Link:
- Previous Recommendations:
- For more exciting content, you can check out:
- Document and Code Acquisition:
- Body Text
- Counter dictionary subclass
- OrderedDict (Ordered Dictionary)
- defaultdict default value dictionary
- ChainMap Mapping Chain
- Base classes for custom dictionaries, lists and strings

Abstract:
In Python, the collections module provides a set of efficient and powerful container data types that extend the built-in basic data types such as list, tuple, dict, etc. These container data types can offer more concise and efficient solutions when dealing with specific problems.
Original Link:
Previous Recommendations:
You who are learning embedded systems, don’t you still know Object Oriented yet? ?!
For more exciting content, you can check out:
Speed Up Your Python: A Quick Guide to Python Parallel Computing
Understand the Debugging Principle of CM3 Microcontrollers in One Article
The "Secret Martial Arts Manual" for Computer Science Competitions
Avnet ZUBoard 1CG Development Board — A New Choice for Deep learning
SenseCraft deploys models to the Grove Vision AI V2 image processing module
Document and Code Acquisition:
You can download the document via the following link:
https://github.com/leezisheng/Doc

This document mainly introduces how to use Python for Object Oriented programming, which requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the slave computer as application examples. Meanwhile, it uses the Sourcetrail code software to visualize the code for reading to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
Python comes with built-in data types and methods, and the collections module provides additional high-performance data types based on these built-in types. For example, a basic dictionary does not support order preservation, while a dictionary constructed with the OrderedDict class from the collections module does. These extended classes in the collections module are extremely useful; mastering this module proficiently can greatly simplify Python code and enhance both the elegance and runtime efficiency of your Python programs.

Among them, the named tuple namedtuple and deque deque have been mentioned in previous articles, and we will explain the other data types here.
Counter dictionary subclass
Counter is a subclass of dictionary designed for counting, which is primarily used to tally the occurrences of hashable objects. It supports common counting operations such as retrieving the most frequent elements and calculating the total count, and its most typical application lies in word frequency statistics in text processing.
from collections import Counter
# Count the occurrences of each character in the string
c = Counter('abracadabra')
print(c) # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
# Count the occurrences of elements in the list
c = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple'])
print(c) # Counter({'apple': 3, 'banana': 2, 'orange': 1})
# Get the most common elements
print(c.most_common(1)) # [('apple', 3)]
# Update counts
c.update(['apple', 'kiwi'])
print(c) # Counter({'apple': 4, 'banana': 2, 'orange': 1, 'kiwi': 1})
# Decrease counts
c.subtract(['banana', 'orange'])
print(c) # Counter({'apple': 4, 'banana': 1, 'kiwi': 1, 'orange': 0})OrderedDict (Ordered Dictionary)
OrderedDict is a subclass of dictionary that records the insertion order of elements. Since Python 3.7, built-in dictionaries also preserve insertion order, but OrderedDict still provides some additional methods, such as move_to_end and other methods to adjust the position of elements.
from collections import OrderedDict
# Create an OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od) # OrderedDict([('a', 1), ('b', 2), ('c', 3)])
# Move an element to the end
od.move_to_end('a')
print(od) # OrderedDict([('b', 2), ('c', 3), ('a', 1)])
# Move an element to the beginning
od.move_to_end('c', last=False)
print(od) # OrderedDict([('c', 3), ('b', 2), ('a', 1)])defaultdict default value dictionary
defaultdict is a subclass of dictionary that provides a default value mechanism. When accessing a non-existent key, it will automatically create a default value instead of throwing a KeyError.
from collections import defaultdict
# Use list as the default factory
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
print(dd) # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
# Use int as the default factory (suitable for counting)
dd = defaultdict(int)
dd['apples'] += 1
dd['oranges'] += 2
print(dd) # defaultdict(<class 'int'>, {'apples': 1, 'oranges': 2})
# Use lambda to customize the default value
dd = defaultdict(lambda: 'unknown')
print(dd['name']) # Output: 'unknown'ChainMap Mapping Chain
ChainMap is a class designed to treat multiple dictionaries or mappings as a single unified mapping. It maintains a list of dictionaries and searches through them in sequence when performing lookups. It can combine multiple dictionaries into one logical mapping, and any modification to the dictionaries within the ChainMap will be reflected across the entire mapping, while also allowing control over the priority of dictionaries during lookups. It is commonly used in configuration management to merge multiple configuration dictionaries into a single configuration mapping, or to implement nested scopes, such as looking up local and global scopes during variable resolution.
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'c': 5, 'd': 6}
# Create a ChainMap
cm = ChainMap(dict1, dict2, dict3)
print(cm) # ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6})
# Look up a key
print(cm['a']) # Output: 1
print(cm['b']) # Output: 2 (from dict1)
print(cm['c']) # Output: 4 (from dict2)
# Add a new key
cm['e'] = 7
print(dict1) # {'a': 1, 'b': 2, 'e': 7}
# Update priority
cm = cm.new_child(dict3)
print(cm) # ChainMap({'c': 5, 'd': 6}, {'a': 1, 'b': 2, 'e': 7}, {'b': 3, 'c': 4}, {'c': 5, 'd': 6})Base classes for custom dictionaries, lists and strings
UserDict, UserList and UserString are base classes provided for users to create custom dictionaries, lists and strings. By encapsulating built-in data types, they make inheritance and extension simpler and safer. They provide methods that can be inherited and overridden to simplify the implementation of custom containers; internally, they use an independent storage structure to avoid directly modifying the behavior of built-in types. They are commonly used to implement containers with specific behaviors, such as automatic key conversion, element type restriction, etc.
from collections import UserDict, UserList, UserString
# Custom dictionary, all keys converted to lowercase
class MyDict(UserDict):
def __setitem__(self, key, value):
super().__setitem__(key.lower(), value)
md = MyDict()
md['A'] = 1
print(md) # {'a': 1}
# Custom list, only integers can be added
class MyList(UserList):
def append(self, item):
if isinstance(item, int):
super().append(item)
else:
raise TypeError('Only integers are allowed')
ml = MyList()
ml.append(1)
print(ml) # [1]
# ml.append('a') # Raises TypeError
# Custom string, all characters uppercase
class MyString(UserString):
def upper(self):
return MyString(self.data.upper())
ms = MyString('hello')
print(ms.upper()) # 'HELLO'