@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic (No. 3136 / 12833)
The default dict was introduced. It seems to initialize the contents of the dictionary by giving a function as an argument.
reference: Python »Documents» Python Standard Library »8. Data Types» 8.3.4.1. Example of using defaultdict
I've tried.
http://ideone.com/cg9rZj
import collections
word_counter = collections.defaultdict(int)
for word in ['daemon', 'demon', 'demoon', 'demon', 'demon', 'daemon']:
word_counter[word] += 1
print(word_counter)
run
defaultdict(<class 'int'>, {'demoon': 1, 'daemon': 2, 'demon': 3})
The same process can be done using Counter ()
.
@ 3184
I've tried. http://ideone.com/CSKsOO
import collections
wordlist = ['daemon', 'demon', 'demoon', 'demon', 'demon', 'daemon']
word_counter = collections.Counter(wordlist)
print(word_counter)
run
Counter({'demon': 3, 'daemon': 2, 'demoon': 1})
There is an example of using defaultdict to group a sequence of (key, value) pairs into a dictionary of lists.
http://ideone.com/FryteV
import collections
seq = [('7of9', 47), ('Janeway', 314), ('Kim', 2718), ('7of9', 6022)]
dct = collections.defaultdict(list)
print(seq)
for key, value in seq:
dct[key].append(value)
print(dct.items())
run
[('7of9', 47), ('Janeway', 314), ('Kim', 2718), ('7of9', 6022)]
dict_items([('Janeway', [314]), ('7of9', [47, 6022]), ('Kim', [2718])])
Recommended Posts