0

If I have an empty dict: dict={}, and I want to add an set dict["foo"]["bar"]["woo"]="foobar", I would need to manually go through and set dict["foo"]={}; dict["foo"]["bar"]={} .... Is there a more efficient way to do this?

BigP
  • 117
  • 7
  • 1
    [This question](https://stackoverflow.com/questions/13276218/in-python-how-does-the-following-autovivification-class-work) proposes a subclass of `dict` that allows this, though it's more of a Perl idiom than a Python one. So it's a neat trick but I wouldn't use it in production. – Silvio Mayolo Oct 09 '22 at 03:42
  • 1
    `dict["foo"]["bar"]["woo"]="foobar"` isn't a `set`, do you mean a nested dictionary like VoidTwo has shown? – BeRT2me Oct 09 '22 at 03:48

1 Answers1

1

There is nothing built in the language for that, but you could use a 3rdy party language that features this kind of convenience.

It won't be more "efficient" in terms of execution time, though - but their use can make for better code in terms of readability and maintainability in some cases.

One such project is extradict with the NestedData class: it can hold nested lists and dictionaries and address all data with a single string using a dot (.) to separate components:

In [2]: from extradict import NestedData

In [3]: my_data = NestedData()

In [4]: my_data["foo.bar.woo"]="foobar"

In [5]: my_data
Out[5]: {'foo': {'bar': {'woo': <str>}}}
# ^ default repr will just show the types in the leaf records,

In [6]: my_data.data
Out[6]: {'foo': {'bar': {'woo': 'foobar'}}}  
# ^ accessing the `.data` attribute retrieves your
# data as plain dicts and lists.


In [7]: my_data["foo.bar.woo"]
Out[7]: 'foobar'

Disclaimer: I am extradict's author and maintainer.

jsbueno
  • 99,910
  • 10
  • 151
  • 209