LoginSignup
1
0

More than 1 year has passed since last update.

python 辞書の欠損処理について

Last updated at Posted at 2022-12-13

辞書の欠損処理の方法

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

exam.py in方式
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}
exam.py2 例外あり

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}
exam3.py getメッソド

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内の要素をカウントしてくれる

exam4.py
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の引数には、初期化時に実行する関数を
記述します。

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

exam5.py
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

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0