#๐Ÿ”’ is there a way to 'create and set if not exists' when accessing nested dictionaries

12 messages ยท Page 1 of 1 (latest)

bleak bane
#

Apologies for the nooby question but I was just having some trouble finding out how to elegantly set things in my nested dicts

take this for example

self.my_dict['firstkey']['secondkey']['thirdkey'] = True

this would throw KeyError if 'firstkey' was not in the dictionaries keys..
and then it would do the same if 'secondkey' wasn't in that entries keys, you get the point.

Ideally when I ran this code if each key was not in place it would be automatically created without me having to write guards around everything to prevent KeyErrors..

am I missing something?

also as a bonus question is there any structure that exists that is like a dictionary but accepts ints as keys? because it's kind of annoying to put str() everywhere. thanks!

exotic tinselBOT
#

@bleak bane

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

solar ice
#
>>> class rdd(defaultdict):
...     def __init__(self, *args, **kwargs):
...             super().__init__(rdd, *args, **kwargs)
... 
>>> x = rdd()
>>> x["a"]["b"]["c"]
rdd(<class '__main__.rdd'>, {})
>>> x
rdd(<class '__main__.rdd'>, {'a': rdd(<class '__main__.rdd'>, {'b': rdd(<class '__main__.rdd'>, {'c': rdd(<class '__main__.rdd'>, {})})})})
>>> x["a"]["b"]["c"]["d"] = True
>>> x
rdd(<class '__main__.rdd'>, {'a': rdd(<class '__main__.rdd'>, {'b': rdd(<class '__main__.rdd'>, {'c': rdd(<class '__main__.rdd'>, {'d': True})})})})

this is a defaultdict which exhibits the behavior you want, although it's probably not ideal due to the subclass

solar ice
#

Sure, but i am fairly sure there's a library out there that's actually well-tested and has better support in general

bleak bane
#

no defaultdict is probably exactly what I want

#

I had heard of the "setdefault" and "getdefault" functions when I looked this stuff up

#

but this solves my question

exotic tinselBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

๐Ÿ”’ is there a way to 'create and set if not exists' when accessing nested dictionaries