⛏️📊 Simplifying Counting with python dict : A Small Trick for Big Wins
- Julia
- Mar 11, 2025
- 1 min read
Updated: Apr 26, 2025
During a geology training session, we were working with lithofacies data from a drillhole. My student was trying to count the occurrences of different facies in a dictionary, but hit a "KeyError" while updating the count. They found it a bit strange—like trying to assign a rock type to a drill core that doesn't exist yet. 🤔🪨
Here’s the problematic code:

It wasn’t long before I introduced them to defaultdict, which works like a geologist's trusty hammer—always ready, no surprises. With defaultdict(int), any missing facies is automatically initialized to 0 without triggering an error: 🔨💡

Output:

Now the dictionary behaves like a reliable tool in the field—keeping track of your facies without any hiccups. 🌍🧭
So next time you're counting facies in a drillhole, remember defaultdict. It's a simple trick that saves time and avoids unnecessary confusion, letting you focus on what really matters: interpreting the rock layers beneath your feet. 💎📉


Comments