Code Like a Pythonista: Idiomatic Python

Dictionary and Iterators

Dictionaries implement a sq_contains slot that implements the same test as the has_key() method. This means that we can write

Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write

which is equivalent to, but much faster than

as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

Add methods to dictionaries that return different kinds of iterators explicitly:

This means that for x in dict is shorthand for for x in dict.iterkeys().

Other mappings, if they support iterators at all, should also iterate over the keys. However, this should not be taken as an absolute rule; specific applications may have different requirements.

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.

Source: http://www.omahapython.org/IdiomaticPython.html

Comments are closed.

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑