Handling missing dict keys, revisited — Stable Diffusion…
    Neura MarketNeura Market/Stable Diffusion
    ChatGPTChatGPTClaudeClaudeGeminiGeminiCursorCursorGrokGrokPerplexityPerplexityStable DiffusionStable Diffusion
    DeepSeekDeepSeekCoPilotCoPilotMidjourneyMidjourney
    View All Directories
    OverviewPromptsBlogVideosGuidesCoursesCommunityModelsLoRAsComfyUI WorkflowsTrending
    Stable DiffusionBlogHandling 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
    Context bankruptcy: The case for strategic forgetting for AI Agentsai

    Context bankruptcy: The case for strategic forgetting for AI Agents

    Most of us have seen a coding agent fail to complete a task we know it can do. We just don't...

    J
    James O'Reilly
    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestrationgooglecloud

    Parallel Compliance Engine: Drive-to-Sheets Multi-Agent Orchestration

    When building Generative AI applications, developers often encounter a massive bottleneck: sequential...

    A
    Aryan Irani
    Is It Ethical to Post and Ask About Circuits on Dev.to?discuss

    Is It Ethical to Post and Ask About Circuits on Dev.to?

    I’ve been thinking about sharing some electronic circuit posts on Dev.to — small circuits, DIY...

    C
    codebunny20
    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limitsagents

    The One-Click Exporter: AI Studio Antigravity, Probed to Its Limits

    What nobody tells you about exporting your multi-agent prototype to a local workspace. Every...

    L
    leslysandra
    Guarding the till while autonomous data agents do the diggingagenticarchitect

    Guarding the till while autonomous data agents do the digging

    Autonomous agents are genuinely good at answering messy business questions. Give one an LLM and a set...

    S
    Sireesha Pulipati
    Return on Attention: Why AI Code Reviews Are Wearing Us Outai

    Return on Attention: Why AI Code Reviews Are Wearing Us Out

    PR volume went up, ticket quality didn't, and the gap got filled with LLMs on both sides of the review: bots reviewing, bots replying, bots occasionally arguing with bots about priorities that only existed in a teammate's head. Our CEO named the actual problem, and it's bigger than code review.

    C
    christine

    Stay up to date

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

    Neura Market LogoNeura Market

    Discover the best AI prompts, plugins, and resources for Stable Diffusion 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.

    Ready-made automations for this

    Workflows from the Neura Market marketplace related to this Stable Diffusion resource

    • Automate GitHub Webhook Responses with Error Handlingn8n · $19.99 · Related topic
    • Automated Media Handling for Patient Communication via WhatsAppn8n · $19.99 · Related topic
    • Edge Device Log Compressor for Efficient Data Handlingn8n · $19.99 · Related topic
    • Efficient MQTT Message Handling for Language Translation Workflowsn8n · $18.15 · Related topic
    Browse all workflows