#DefaultDict
Friday brings #Python

With defaultdict + lambda you can build a nested tree that never raises a KeyError. Isn't that cool?
September 25, 2026 at 6:58 PM
Quick recap of ByteLex's Cross-Tokenization and the faults leading to successes
negdev: > > import numpy as np > from collections import Counter, defaultdict > from scipy.stats import spearmanr > > def utf8_bytes(s): > return np.frombuffer(s.encode("utf-8"), dtype=np.uint8) > > def three_byte_windows(b): > if len(b) < 3: > return np.empty((0,3), dtype=np.uint8) > return np.stack([b[i:i+3] for i in range(len(b)-2)], axis=0) > > def build_map_for_tokenizer(vocab): > """ > vocab: dict {token: weight} > Returns: > occupancy: Counter of 3-byte windows > continuation: dict {window: Counter(next_byte)} > endability: Counter of window endings > """ > occupancy = Counter() > continuation = defaultdict(Counter) > endability = Counter() > > for token, weight in vocab.items(): > b = utf8_bytes(token) > windows = three_byte_windows(b) > Below is the 3‑byte structural map code I used. It’s designed to isolate UTF‑8 byte‑level regularities inside the tokenizer’s vocabulary, without assuming any semantic structure or downstream behavior. The goal is to quantify purely structural signals (occupancy, continuation bias, and endability) that might correlate with per‑token difficulty or stability across training stages. The pipeline is intentionally simple: • Convert each token to its raw UTF‑8 byte sequence. • Extract all consecutive 3‑byte windows. • Accumulate three statistics: – occupancy: how often each 3‑byte window appears – continuation: conditional distribution of the next byte after each window – endability: how often a window appears at the end of a token These three quantities form the basis for dominance and endability metrics: dominance = max(next_byte_count) / sum(next_byte_counts) endability = endability_count / occupancy_count The code: import numpy as np from collections import Counter, defaultdict def utf8_bytes(s): return np.frombuffer(s.encode(“utf-8”), dtype=np.uint8) def three_byte_windows(b): if len(b) < 3: return np.empty((0,3), dtype=np.uint8) return np.stack([b[i:i+3] for i in range(len(b)-2)], axis=0) def build_map_for_tokenizer(vocab): occupancy = Counter() continuation = defaultdict(Counter) endability = Counter() for token, weight in vocab.items(): b = utf8_bytes(token) windows = three_byte_windows(b) for i, w in enumerate(windows): w_tuple = tuple(w.tolist()) occupancy[w_tuple] += weight # continuation if i + 3 <= len(b) - 1: next_byte = int(b[i+3]) continuation[w_tuple][next_byte] += weight # endability if i == len(windows) - 1: endability[w_tuple] += weight return occupancy, continuation, endability This structure is intentionally agnostic to the model’s training dynamics. It only captures the tokenizer’s byte‑level geometry. The idea was to check whether any of these structural biases (especially dominance and endability) correlate with per‑word exam accuracy, difficulty slopes, or the stability of difficulty across training stages. If you run a 2‑byte / 3‑byte / 4‑byte variant, the same counters generalize directly. It’s cheap to compute and can be scored against existing per‑word accuracies without additional training runs.
discuss.huggingface.co
September 18, 2026 at 7:18 PM
ABC175-E「Picking Goods」を解きました✅

3次元配列でMLE、defaultdictでTLEと苦戦しましたが、行ごとに使い回す2次元配列に圧縮してAC。メモリと速度のバランスを取る過程が学びになりました🎁

https://gist.github.com/maehrm/238def5fd85ab6a6a7043277189d1215

#AtCoder #競技プログラミング
E - Picking Goods https://atcoder.jp/contests/abc175/tasks/abc175_e
E - Picking Goods https://atcoder.jp/contests/abc175/tasks/abc175_e - abc175_e.py
gist.github.com
September 6, 2026 at 9:19 AM
ABC183-F「Confluence」を解きました✅

UnionFindでグループを管理し、各リーダーにクラス人数をdefaultdictで保持。マージテク(小さい方を大きい方に統合)で計算量を抑えました🏫

https://gist.github.com/maehrm/b45bc22869475a70fb1fbf57e5500158

#AtCoder #競技プログラミング
F - Confluence https://atcoder.jp/contests/abc183/tasks/abc183_f
F - Confluence https://atcoder.jp/contests/abc183/tasks/abc183_f - abc183_f.py
gist.github.com
August 30, 2026 at 1:28 AM
📦 sunaoka/defaultdict-php v1.1.0



🔗 https://github.com/sunaoka/defaultdict-php
August 24, 2026 at 5:10 AM
“The defaultdict is very handy, but I find that it's rarely useful enough that I feel the need to use it.”

Read more 👉 pym.dev/default-dict...

#Python
https://pym.dev/default-dictionary-values/
pym.dev
August 3, 2026 at 6:16 PM
Want to create a dict of lists in #Python? You can use defaultdict:

from collections import defaultdict

places = defaultdict(list)
while True:
city, country = input('Place: ').split()
places[country].append(city) # list is guaranteed
print(places)
July 3, 2026 at 3:30 PM
@Salty

Doesn't defaultdict do this? I feel like maybe it does
June 25, 2026 at 10:02 PM
defaultdict, das passiv-aggressiv eine leere Liste zurückgibt, wenn der Schlüssel nicht vorhanden ist
June 2, 2026 at 11:10 AM
"What does defaultdict(float) mean in Matplotlib?" I'm glad you asked!

defaultdict(float) is a dictionary that automatically starts any new key at 0.0
#Python #PythonTips #100DaysofCode
May 22, 2026 at 9:52 PM
💡 Tip #98 en #Python
¡Agrupa con collections.defaultdict!
# ✅ MÉTODO PYTHONIC (Limpio y directo con defaultdict ✨)

Código más limpio: Eliminas ramas condicionales innecesarias dentro de tus bucles.

🎥 www.youtube.com/@josecodetech/
#Programacion
May 8, 2026 at 4:42 PM
Pythonのdefaultdictでは参照しただけでも要素が増えるから、そのせいで実行速度もメモリも増えたりすることがある、
これはPythonですが少し話題に上がっていたので。
May 4, 2026 at 7:34 AM
# Slightly cursed Python patterns: nested defaultdicts
from collections import defaultdict as dd
d = dd(lambda: dd(lambda: dd(list)))
April 15, 2026 at 7:15 PM
How to use #Python and a defaultdict to return a custom message if the key does not exist in the dictionary 🐍🚀
April 1, 2026 at 9:01 AM
💡 Tip #86 en #Python
¡Protege y simplifica tu código con defaultdict! 🚀
Más trucos para escribir código a prueba de balas aquí 🎥 www.youtube.com/@josecodetech/ #JoseCodeTech #Programacion #AprendePython #PythonTips #DefaultDict #CleanCode #Pythonic #DataScience
March 20, 2026 at 5:29 PM
Start simple, get sophisticated as needed.

my_dict.get(k, d): get value or default, once

my_dict.setdefault(k, d): set value if not set

dict.fromkeys(keys, d): make new dict with known keys

Counter(items): mapping that counts occurrences

defaultdict(list): mapping that defaults key lookups
February 13, 2026 at 7:24 PM
New video on the many ways to "default" dictionary values.

1. get
2. setdefault
3. fromkeys
4. dict comprehension
5. collections.defaultdict
6. collections.Counter

You shouldn't always reach for defaultdict. Start with the simplest approach that works well for your situation.

#Python
Dictionary default values in Python
YouTube video by Python Morsels
youtu.be
February 13, 2026 at 4:18 PM
When we say "dictionary" in Python we often mean "mapping" (dictionary-like object) thanks to our embrace of duck typing.

Counter, defaultdict, and other dictionary-like objects also tend to support both of those syntaxes.
February 11, 2026 at 11:45 PM
Using #Python defaultdict? Don't pass a value:

d = defaultdict(0) # ❌ Error!

Pass a function that returns the default:

d = defaultdict(int) # int() returns 0
d = defaultdict(list) # list() returns []
d = defaultdict(dict) # dict() returns {}
February 10, 2026 at 4:30 PM
When you explore the `collections` module, you’ll often see `Counter`, `defaultdict`, and `namedtuple` (I prefer `typing.NamedTuple`).

One often-overlooked tool is `ChainMap`:
January 21, 2026 at 6:17 AM
yeah, a great example of a good tip is to use `NamedTuple` from `typing`, rather than the older version from `collections`, as it has a cleaner interface

don’t forget about `defaultdict`

don’t use a mutable object as a default value for a parameter

use `heapq` instead of constantly sorting
January 10, 2026 at 3:54 AM
I've completed "Laboratories" - Day 7 - Advent of Code 2025 #AdventOfCode adventofcode.com/2025/day/7 Used `set()` for part 1 to deal with overlapping beams, moved to `defaultdict(int)` in part 2 to count beams in same position (it's lanternfish day!).
github.com/marcodelmast...
AdventOfCode2025/Day07.ipynb at main · marcodelmastro/AdventOfCode2025
Advent Of Code 2025. Contribute to marcodelmastro/AdventOfCode2025 development by creating an account on GitHub.
github.com
December 7, 2025 at 7:23 AM
Если бы мне не за что было ненавидеть #rust
сегодня я бы ненавидел его за мучения с github.com/pydantic/pyd...
Release v2.41.5 · pydantic/pydantic-core
What's Changed Correct invalid serialization of date/datetime/time/timedelta by pulling downcast checks up by @astei in #1851 avoid getting default values from defaultdict by @davidhewitt in #1853...
github.com
December 4, 2025 at 8:21 PM
In fairness, I’m not sure I’ve used a defaultdict anywhere other than for Advent of Code. 😂
December 2, 2025 at 1:56 PM
I think I've learned about numerous data structures and various python built-in modules from doing (and reading other's solutions) to Advent of Code. I'm pretty sure I'd never seen or used a defaultdict until AoC.
December 2, 2025 at 1:52 AM