Handling missing dict keys, revisited — CoPilot Tips &…
    Neura MarketNeura Market/CoPilot
    ChatGPTChatGPTClaudeClaudeGeminiGeminiCursorCursorGrokGrokPerplexityPerplexityCoPilotCoPilot
    DeepSeekDeepSeekStable DiffusionStable DiffusionMidjourneyMidjourney
    View All Directories
    OverviewRulesPromptsMCPsAgentsGamesBlogVideosGuidesCoursesCommunityPluginsTrending
    CoPilotBlogHandling missing dict keys, revisited
    Back to Blog
    Handling missing dict keys, revisited
    python

    Handling missing dict keys, revisited

    Kelvin Wangonya April 8, 2026
    0 views

    A while back, I wrote a post showing how to handle missing dict keys. In summary: Using...

    A while back, I wrote a post showing how to handle missing dict keys. In summary:

    • Using setdefault
    • Using defaultdict
    • Implementing __missing__

    While the advice there still stands, I've been reading through Fluent Python and came across two things worth being aware of when subclassing dict:

    1. __contains__ doesn't call __missing__, so k in d returns False for keys not yet set, even if __missing__ would handle them
    2. dict.get doesn't call __missing__, so .get(k) won't use your custom default

    Both are by design and often what you want. __missing__ is only used by d[key], not other dict methods. Even defaultdict follows the same rule: only d[key] triggers the default factory and methods like .get() and in do not.

    Overriding get is tempting but tricky. A naive implementation might look like this:

    class M(dict):
        def __missing__(self, key):
            value = "my default value"
            self[key] = value
            return value
    
        def get(self, key, default=None):
            try:
                return self[key]  # triggers __missing__ if key is absent
            except KeyError:
                return default    # dead code, never reached
    

    This doesn't work. self[key] calls __missing__ instead of raising KeyError, so the except block is unreachable and default is effectively useless:

    >>> m = M()
    >>> m.get("x", "fallback")
    'my default value'          # expected "fallback", got __missing__ value instead
    >>> m
    {'x': 'my default value'}  # side effect: key was set in the dict
    

    There's no clean way to honour both the __missing__ default and the default parameter in get. It's better to accept that get and __missing__ serve different purposes and leave get alone. Note that this applies to dict subclasses specifically. If you subclass UserDict instead, get calls __getitem__ internally and __missing__ is triggered. With a dict subclass, get is implemented in C and bypasses __getitem__ altogether. The behaviour is inconsistent across the standard library depending on which base class you use.

    As for __contains__, overriding it is a design decision. If your subclass provides a value for every possible key, returning True always can be reasonable:

    def __contains__(self, key):
        return True
    

    Only thing to keep in mind in this case is that "x" in m returns True even when m is {}, which looks confusing.

    Tags

    python

    Comments

    More Blog

    View all
    Five Gemma-4 models, one accelerator: what porting E2B 31B to AWS Inferentia2 taught megemma

    Five Gemma-4 models, one accelerator: what porting E2B 31B to AWS Inferentia2 taught me

    I ported the whole Gemma-4 family — E2B, E4B, 12B, 31B, and the 26B-A4B MoE — to run on...

    X
    xbill
    Hey DEV, I'm Tobore. Let's actually connect.community

    Hey DEV, I'm Tobore. Let's actually connect.

    Hey DEV, I'm Tobore. Let's actually connect. I've been on here for a while now, mostly writing and...

    L
    Laurina Ayarah
    I burned through thousands of AI tokens. Then a friend did it for freeai

    I burned through thousands of AI tokens. Then a friend did it for free

    (yep, kinda clickbait, just for the funsies 😊) At the beginning of the year, I relaunched my...

    P
    Paulo Henrique
    Claude might be saturating your machineai

    Claude might be saturating your machine

    My laptop was sitting idle with the fan at full tilt. Nothing was running that I knew of. The culprit...

    S
    Sidhant Panda
    Automated GitHub Code Reviews Using Google Geminigithubactions

    Automated GitHub Code Reviews Using Google Gemini

    I Built a Thing! TL;DR — Google Gemini-based Pull Request reviews and Issue Triaging for...

    D
    Darren "Dazbo" Lester
    What is an "agentic harness," actually?ai

    What is an "agentic harness," actually?

    I've been hearing the word "harness" thrown around a lot lately. I assumed it just meant "the IDE" or...

    T
    Tilde A. Thurium

    Stay up to date

    Get the latest CoPilot prompts, rules, and resources delivered to your inbox weekly.

    Neura Market LogoNeura Market

    Discover the best AI prompts, plugins, and resources for CoPilot and more.

    Content Types

    • Rules
    • Prompts
    • MCPs
    • Agents
    • Guides

    Platforms

    • ChatGPT Directory
    • Claude Directory
    • Gemini Directory
    • Cursor Directory
    • Grok Directory
    • Perplexity Directory
    • DeepSeek Directory
    • CoPilot Directory
    • Stable Diffusion Directory
    • Midjourney Directory
    • All Directories

    Resources

    • Blog
    • Documentation
    • Help Center
    • Marketplace

    Legal

    • Privacy Policy
    • Terms of Service

    © 2026 Neura Market. All rights reserved.

    |

    Not affiliated with any AI platform vendors.

    Neura Market

    Custom AI Systems & Services

    Our team of experienced AI builders will help build custom AI systems, workflows, and solutions for your business.

    Request custom work

    Ready-made automations for this

    Workflows from the Neura Market marketplace related to this CoPilot resource

    • Handling Appointment Leads and Follow-Up with Twilio, Cal.com, and AIn8n · $24.99 · Related topic
    • Redis Locking for Concurrent Task Handlingn8n · $14.99 · Related topic
    • Handling Job Application Submissions with AI and N8n Formsn8n · $14.99 · Related topic
    • Automated Sonarr Missing Episode Finder with Quality & Language Filteringn8n · $9.99 · Related topic
    Browse all workflows