collections.defaultdict()

defaultdict is almost the same as dict which can be assigned by this statement:

1

d = {'name': 'frank'}

defaultdict provides a function which will be invoked when we use a non-exists key to access the value in the defaultdict. When we want to get the value by a key which does not exist in the dict, dict will raise a KeyError Exception. We can use d.get(KEY, DEFAULT_VALUE) to define the value we will get if the key does not exist. It is okay but not an easy work-around. For example, I have a dict named writer_book_dict and its key is writers’ name and value is books’ name. When I get the value by a non-exist writer, it should return ‘NO BOOKS’. Let’s see how we can deal it with dict and defaultdict.

We can use a complex function in initialize the defaultdict. Furthermore, we can also define the data structure of the value in the defaultdict. Let’s see an example, we need to make a classification of a short paragraph by the first letter of each world. It is to say, ‘I am a student and I like sports’ -> {'a': ['am', 'a', 'and'], 'i': ['it', 'is', 'i'], 'l': ['like'], 's': ['student', 'sports']}. If we use default we must judge if the key exists and if it does not exist, we need to initialize with an empty list like below:

from collections import defaultdictparagraph = 'I am a student and I like sports'word_defaultdict = defaultdict(list)for word in paragraph: word_defaultdict[word[0]].append(word)

If we want to uniq the element of word_defaultdict, we can simply initialize word_defaultdict by defaultdict(set).

bisect

bisect is used to insert element into an sorted list and keep the list sorted. bisect module have six methods:

bisect

bisect_left

bisect_right

insort

insort_left

insort_right

Methods start with bisect will return the index of the element you need to insert. Those start with insort will make change into list directly and return nothing. The difference between left and right will affect the result of operation only when the element you want to insert does exist in the list and left will return the index left of this existed-element and right return the right position. Please remark that bisect is the same as bisect_right and insort is the same as insort_right. Let’s see some examples.