見出し画像

辞書オブジェクト 【defaultdict】

4月後半から超ロングGWがあり、横浜トライアスロンがありとバタバタ忙しく、時間が経ってしまいました。夏日も増えてきて、好きな季節になってきましたが、勉強の方もぼちぼち再開して行きたいと思います。
※横浜トライアスロン 2019については別途ブログ執筆予定でございます。

今日は辞書型オブジェクト defaultdict の使い方を少しだけまとめ。
辞書型のオブジェクトはkeyを追加する度に そのkeyの初期化が必要になるのですが、collections moduleの defaultdictクラスを用いるとサクッとシンプルにコードを書けるとのこと。

まずは初期化のパターン

d = {}
lst = ["foo", "bar", "pop", "pop", "foo", "popo"]
for key in lst:
   if key in d:
       d[key] += 1
   else:
       d[key] = 1
print(d)

## 実行結果
{'foo': 2, 'bar': 1, 'pop': 2, 'popo': 1}

defaultdictを使ったパターン

from collections import defaultdict

d = defaultdict(int)
lst = ["foo", "bar", "pop", "pop", "foo", "popo"]
for key in lst:
   d[key] += 1
print(d)

## 実行結果
defaultdict(<class 'int'>, {'foo': 2, 'bar': 1, 'pop': 2, 'popo': 1})

ということで、defaultdictを用いて descriptionに出現する文字の出現回数を調べるコードを練習してみました。

from collections import defaultdict


# 文字列 from wikipedia
description = \
"Machine learning (ML) is the scientific study of algorithms and statistical models that computer systems " + \
"use to effectively perform a specific task without using explicit instructions, relying on patterns and inference instead." + \
"It is seen as a subset of artificial intelligence. Machine learning algorithms build a mathematical model based on sample data, " + \
"known as training data, in order to make predictions or decisions without being explicitly programmed to perform the task.[1][2]:2 " + \
"Machine learning algorithms are used in a wide variety of applications, such as email filtering, and computer vision, where it is " + \
"infeasible to develop an algorithm of specific instructions for performing the task. Machine learning is closely related to " + \
"computational statistics, which focuses on making predictions using computers. The study of mathematical optimization delivers methods, " + \
"theory and application domains to the field of machine learning. Data mining is a field of study within machine learning, and focuses on " + \
"exploratory data analysis through unsupervised learning.[3][4] In its application across business problems, machine learning is also " + \
"referred to as predictive analytics."

# defaultdict指定
freq = defaultdict(int)

# how many the charactor appear

for i in description:
   freq[i] += 1
   
# 辞書.items() でソートして、(key, value)の2つめの要素を指定(lambda使用)、降順に10個だすとして reverseを使う
print(sorted(freq.items(), key = lambda x: x[1], reverse=True)[:10])

## 実行結果
[(' ', 168), ('i', 109), ('e', 94), ('a', 87), ('t', 82), ('n', 77), ('s', 76), ('o', 63), ('r', 53), ('l', 46)]

以上でした。また次も pythonの便利な使い方を見ていきたいとおもいます。

今回の"note"を気に入って頂けましたら、是非サポートをお願いいたします!