Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7998101
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T15:08:06+00:00 2026-06-04T15:08:06+00:00

There are at least two decent implementations of nested dictionary I’ve come across on

  • 0

There are at least two decent implementations of nested dictionary I’ve come across on SO, one is to use defaultdict, and the other is to subclass dict.

Both methods work fine for most functionalities, except that they both have a side-effect when accessing a non-existent key-value pair: it creates an empty dictionary for that key, stores that and returns it.

Ideally, I would like an implementation which would return None without creating an entry (e.g. an empty dictionary) upon an attempted access to a non-existent key. Is this feasible?

p.s. I am aware that we can avoid nested dictionary by using tuples as keys, but this implementation does not work me as I need to access the collection of entries at each level of the nested dictionary.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T15:08:07+00:00Added an answer on June 4, 2026 at 3:08 pm

    You must give up your requirement of returning None if you wish d[key][subkey] = value to work with missing keys. If d[key] is None, d[key][subkey] = value is equivalent to None[subkey] = value, which cannot work.

    What you can do with missing values is to return an empty dict-like object without assigning it to a key just yet. If that object holds a reference to the parent, the assignment can be delayed until there is an explicit assignment down the hierachy.

    An example implementation (this is incomplete, you must do more than override setitem to have a fully functional dict subclass):

    class NestedDict(dict):
        def __init__(self, parent=None, parentkey=None):
            self.parent = parent
            self.parentkey = parentkey
    
        def __missing__(self, key):
            return NestedDict(self, key)
    
        def __setitem__(self, key, value):
            if self.parent is not None:
                self.parent[self.parentkey] = self
                self.parent = None
            super(NestedDict, self).__setitem__(key, value)
    
    >>> d = NestedDict()
    >>> d[1][2][3] = 4
    >>> d[2]
    {}
    >>> d.keys()
    [1]
    >>> d[1][2][3] 
    4
    

    An alternative approach would be to override __getitem__ and __setitem__ to do a nested lookup when the key is a tuple. This version gives a KeyError from __getitem__ for missing keys in order to be consistent with regular dict. You can change it easily to return None instead if you wish.

    class NestedDict(dict):
        def __getitem__(self, key):
            if isinstance(key, tuple):
                try:
                    x = self
                    for k in key:
                        x = x[k]
                    return x
                except (KeyError, TypeError):
                    raise KeyError(key)
            else:
                return super(NestedDict, self).__getitem__(key)
    
        def __setitem__(self, key, value):
            if isinstance(key, tuple):
                d = self
                for k in key[:-1]:
                    d = d.setdefault(k, NestedDict())
                d[key[-1]] = value
            else:
                super(NestedDict, self).__setitem__(key, value)
    
    >>> d = NestedDict()
    >>> d[1,2,3] = 4
    >>> d[1,2,3]
    4
    >>> d[1,2,4]
    KeyError: (1, 2, 4)
    >>> d
    {1: {2: {3: 4}}}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

There's at least two Bcrypt implementations in C out there: The original: http://bcrypt.sourceforge.net/ Openwall's:
I remember once reading that there were at least two other alternatives invented roughly
It looks like there are (at least) two options for getting nant to use
I am trying to print 1 if there are at least two of the
From previous post, I learnt that for there are two ways, at least, to
For detect undefined variable which have been declared in javascript there at least two
There are at least two methods for copying a file in C/C++: procedurally and
Well, there are at least two low-level ways of determining whether a given number
There are at least two ways that I know of to write a Symbian
As most people know there are at least two (easy) ways to findout if

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.