Python Forum
[solved] subdictionaries path as variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[solved] subdictionaries path as variable
#1
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
Reply
#2
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.
Reply
#3
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.
Reply
#4
Thanks, that's what I've been looking for
Reply
#5
# 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=": ")
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  working directory if using windows path-variable chitarup 2 682 Nov-28-2023, 11:36 PM
Last Post: chitarup
  SOLVED variable as tuple name krayon70 7 1,764 Apr-09-2022, 03:30 PM
Last Post: krayon70
  Get latest version off website and save it as variable [SOLVED] AlphaInc 5 1,892 Nov-14-2021, 09:00 PM
Last Post: DeaD_EyE
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,151 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  [solved] Variable number of dictionnaries as argument in def() paul18fr 11 6,026 Apr-20-2021, 11:15 AM
Last Post: paul18fr
  How to include Variable in File Path penahuse 3 7,222 Jan-05-2020, 03:08 AM
Last Post: ichabod801
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,673 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908

Forum Jump:

User Panel Messages

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