Python> dictionary / collections> defaultdict () / Counter ()

@ 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

counter

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})

Dictionary grouping of key, value pair sequences

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

Python> dictionary / collections> defaultdict () / Counter ()
Python dictionary
[Python] dictionary
Python dictionary
[Python] Memo dictionary
[Python] Dictionary (hash)
Python basics: dictionary
Python collections module
Python3 List / dictionary memo
Python Dictionary Beginner's Guide
Python list, for statement, dictionary
Create a dictionary in Python
Avoid KeyError in python dictionary
Python> dictionary> get ()> optional value
Notes on Python and dictionary types
Expansion by argument of python dictionary
Replace dictionary value with Python> update ()
Python for super beginners Python # dictionary type 1 for super beginners
Create a nested dictionary using defaultdict
Basic grammar of Python3 system (dictionary)
Python for super beginners Python # dictionary type 2 for super beginners