Python Forum
[solved] subdictionaries path as variable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [solved] subdictionaries path as variable (/thread-33684.html)



[solved] subdictionaries path as variable - paul18fr - May-16-2021

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


RE: subdictionaries path as variable - bowlofred - May-16-2021

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.


RE: subdictionaries path as variable - perfringo - May-17-2021

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}}}



RE: [solved] subdictionaries path as variable - paul18fr - May-18-2021

Thanks, that's what I've been looking for


RE: [solved] subdictionaries path as variable - DeaD_EyE - May-18-2021

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