Python Forum
[solved] subdictionaries path as variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[solved] subdictionaries path as variable

I'm using different levels of subdictionnaries in order to sort types of data (In the same idea of directories and sub-directories) ; it works fine. To update or add new ones, I need to provide explicitly the structure such as:
In the previous example, everything is variable (subdict, subsubdict and so on); I'm wondering if ther's a way to remplace what I'm calling here a "path" by a variable, i.e. "[subdict][subsubdict]" by a kind of "path = [subdict][subsubdict]"?

Of course I can use the next code, but it's better to avoid it, isn't it?
path = '[subdict][subsubdict]'
exec("MyDict%s.update(Newdict)" % path )
Thanks for any suggestion.

If by "path" you meant like a list of keys: path = ["subdict", "subsubdict"]. then you could do:

mydict = {"subdict": {"subsubdict": {'a': 1}}}


#path traversal
path = ["subdict", "subsubdict"]
s = mydict
for element in path:
    s = s[element]
{'a': 1} {'a': 1}
There's no error-checking here. So if your path is incorrect, the index will fail and you'll get an error.
Probably I don't get what and why is needed, but in Python everything is object, so you can pass them around as you like. I don't know whether it addresses the problem but one can do this way:

>>> d = {'a': {'b': {'c': 1}}}
>>> nested = d['a']['b']
>>> nested.update({'d':2})
>>> nested
{'c': 1, 'd': 2}
>>> d
{'a': {'b': {'c': 1, 'd': 2}}}
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Thanks, that's what I've been looking for
# definition
MyDict = {"subdict": {"subsubdict": {}}}

# somewhere in code you want to access the sububdict
subdict = "subdict"
subsubdict = "subsubdict"

dict_in_subdict = MyDict[subdict][subsubdict]

# now assigning some values to keys of dict_in_subdict
dict_in_subdict["a"] = "Hello World"
dict_in_subdict["solution"] = 42

# this also affects MyDict because the dict in subsubdict is the same object, where dict_in_subdict points to
For example, you could use this in a loop. Parsing JSON ends often in deep nested structures.
import subprocess
import json

def get_addrs():
    stdout = subprocess.check_output(["ip", "-j", "address"])
    for section in json.loads(stdout):
        addr_info = section["addr_info"]
        ifname = section["ifname"]
        for address in addr_info:
            label = address.get("label")
            name = label or ifname
            print(name, address["local"], sep=": ")
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die:
All humans together. We don't need politicians!

Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 819 Apr-20-2021, 11:15 AM
Last Post: paul18fr
  How to include Variable in File Path penahuse 3 2,786 Jan-05-2020, 03:08 AM
Last Post: ichabod801
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 2,710 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020