辞書の欠損処理の方法

例題として、好きなプログラミング言語についてエンジニアの方々にアンケートを取り、これを辞書で定義します。もともと、プログラミング言語が登録されていない場合は、新たに作成して値を増やしていく。

questionnaire = {
    "python": 1,
    "Rust": 2,
    "C": 0
}

print('アンケート前:', questionnaire)
key = "SQL"

if key in questionnaire:
    count = questionnaire[key]
else:
    count = 0

questionnaire[key] = count + 1
print('アンケート後:', questionnaire)

>>>
アンケート前 {'python': 1, 'Rust': 2, 'C': 0}
アンケート後 {'python': 1, 'Rust': 2, 'C': 0, 'SQL': 1}

questionnaire = {
    "python": 1,
    "Rust": 2,
    "C": 0
}

print('アンケート前:', questionnaire)

key = 'SQL'
try:
    count = questionnaire[key]
except KeyError:
    count = 0
questionnaire[key] = count + 1

print('アンケート後:', questionnaire)


>>>
アンケート前 {'python': 1, 'Rust': 2, 'C': 0}
アンケート後 {'python': 1, 'Rust': 2, 'C': 0, 'SQL': 1}

questionnaire = {
    "python": 1,
    "Rust": 2,
    "C": 0
}

print('アンケート前:', questionnaire)

key = 'SQL'
# keyが存在しない場合はデフォルト値0を返す
count = questionnaire.get(key, 0)
questionnaire[key] = count + 1

print('アンケート後:', questionnaire)

>>>
アンケート前 {'python': 1, 'Rust': 2, 'C': 0}
アンケート後 {'python': 1, 'Rust': 2, 'C': 0, 'SQL': 1}

以上のような、inを使う場合、例外を使う場合、getメソッドを使う場合があるが、getメソッドが、読性が高く、コードが短くなるので一番良いと考えられる。

collectionsモジュールのCounterクラスを使ってみよう!

Counterは、listやdic内の要素をカウントしてくれる

from collections import Counter

numbers = {'one': 12, 'two': 3, 'three': 6}
abc = ['a', 'a', 'a', 'a', 'a', 'c', 'c', 'b', 'b', 'b']

count_number = Counter(numbers)
count_abc = Counter(abc)
print(count_number)
print(count_abc)

>>>
Counter({'one': 12, 'three': 6, 'two': 3})
Counter({'a': 5, 'b': 3, 'c': 2})

defaultdictを使おう!

参考
Python defaultdict の使い方

defaultdictの引数には、初期化時に実行する関数を
記述します。

以下、好きなプログラミング言語に投票した人の名前を値とした辞書を用いてみる。

from collections import defaultdict


class programming:
    def __init__(self):
        self.data = defaultdict(set)

    def add(self, PL, name):
        self.data[PL].add(name)


questionnaire = {
    "python": ['taro', 'jiro'],
    "C": ['saburo'],
    "SQL": ['hanako']
}

P = programming()
P.add("Rust", 'jun')
P.add("Rust", 'mai')
print(P.data)

>>>defaultdict(<class 'set'>, {'Rust': {'mai', 'jun'}})

参考文献

Effective Python

bannerAds