Recently, in the process of coding, I found that the Collections library provides many useful tools for optimizing coding styles and improving development efficiency.

Here are some of my own summaries, combined with online sources.

defaultdict

With dict, a KeyError is raised if the referenced Key does not exist. Defaultdict is used if you want the key to return a default value when it doesn’t exist

Before I touched it, I often used setdafult in my code to set the initial value of the dictionary, but it wasn’t very readable or elegant, like this one:

for cate in res_service_category:
    category_id = cate['id']
    biz_service_category_mapping = self._service_category_data.setdefault(bk_biz_id, {})
    biz_service_category_mapping[category_id] = cate
Copy the code

What if you use DefaultDict? Isn’t that much simpler.

self._service_category_data = defaultdict()
for cate in res_service_category:
    category_id = cate['id']
    biz_service_category_mapping = self._service_category_data[bk_biz_id]
    biz_service_category_mapping[category_id] = cate
Copy the code

OrderedDict

It is well known that with dict, keys are unordered. When iterating over dict, we can’t determine the order of keys.

If you want to keep keys in order, you can use OrderedDict

nodes_category = OrderedDict([('ADD', []),'REMOVE', []),'RETRY'[]])Copy the code

This ensures the order of the dictionary as you traverse it.

namedtuple

Namedtuple is a function that creates a custom tuple, specifies the number of tuple elements, and can refer to elements of the tuple by attributes rather than indexes.

Namedtuple makes it easy to define a datatype that has the invariance of a tuple and can be referenced by attributes.

>>> from collections import namedtuple
>>> Point = namedtuple('Point'['x'.'y'])
>>> p = Point(1.2)
>>> p.x
1
>>> p.y
2
Copy the code

deque

When using lists to store data, accessing elements by index is fast, but inserting and deleting elements is slow because lists are linear storage and are inefficient for large amounts of data.

A DEQUE is a bidirectional list for efficient insert and delete operations, suitable for queues and stacks

>>> from collections import deque
>>> q = deque(['a'.'b'.'c'])
>>> q.append('x')
>>> q.appendleft('y')
>>> q
deque(['y'.'a'.'b'.'c'.'x'])
Copy the code

conclusion

I know that the Use of the Collections library is already familiar to many Python pros and don’t need to read this article. What I want to express is that how to write elegant code, or write perfect code, there is a long way to go, and this is an endless path of improvement, and for every coder, walk on their own road. So, keep moving.