python dict

python dictの使い方

タグ dict defaultdict


概要

  • pythno3からdictの順序が保存されるようになった
    • 二分木での実装に変更された?
  • 順序があるdictはpopitem関数があり、LIFOである
  • setdefault関数があり、キーがない場合に入れる値である
    • 応用すると、トライ木が簡潔に実装できる
  • getは第2引数に、キーが存在しない場合、返す値を設定できる
    • 環境変数が存在しない場合にデフォルト値を返したい時に便利
      • e.g. os.environ.get("DISABLE_TQDM", False)
  • dictにデフォルト値をもたせたいときは、collections.defaultdictを用いる
    • collections.defaultdictは名前空間の関係でpickleでシリアライズできない
    • collections.defaultdictdictの初期化引数に入れることで、Dict[Any, Any]に変換できる

具体例

d = dict(k2=1, k1=2)

assert(d == dict(k1=2, k2=1))
assert(d.popitem() == ("k1", 2))

d["k1"] = 2
assert(d.setdefault("k3", dict()) == {})
assert(d.pop("k1") == 2)

トライ木の実装

WORD_KEY = '$'

trie = {}
for word in words:
    node = trie
    for char in word:
        node = node.setdefault(char, {})
    # mark the existence of a word in trie node
    node[WORD_KEY] = word

typingの応用

  • dict, defaultdictともに専用のタイピングが用意されている
    • それぞれに応じた型ヒントを与えれば良い
from typing import Dict, DefaultDict
import collections

nd: Dict = dict()
dd: DefaultDict = collections.defaultdict(int)

参考