Python Forum

Full Version: [solved] subdictionaries path as variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

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:
MyDict[subdict][subsubdict].update(Newdict)
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.

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

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

#explicit
print(mydict["subdict"]["subsubdict"])

#path traversal
path = ["subdict", "subsubdict"]
s = mydict
for element in path:
    s = s[element]
print(s)
Output:
{'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}}}
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]
print(dict_in_subdict)

# 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
print(MyDict)
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=": ")