r/Python•
freealloc

Using an array of strings as keys to dicts within dicts

I'm a firmware guy, so I'll be the first to admit that my python solution can often be less the elegant.

Anyway as a personal project, I'm parsing a file following the OSC protocol, while has parameters in a similar format to Linux directories (/path/to/paramater) followed by that values for the parameter. In parsing it, I can easily separate the parameter path from the value, but I'm wanting to create dicts within dicts that eventually hold the parameter values. My problem is that the path may have a varying number of "subfolders." Is there a clean way to use an array of the format ["path", "to", "value"] to create and access a dict as d["path"]["to"]["value"] where the number of embedded dicts is variable?

Posted Jun 25, 2016, 8:32 AM UTC

09
maxm•

the easiest way to create multidimensional arrays in python is to use tuples as keys.

paths[('path','to','somewhere')] = 'something'
4
freeallocOP•

I think I'll try u/K900_'s suggestion. Yours is definitely reasonable, but has some issue with the application. It's for an audio console and I'd like to be able to easily access channels in order to do things like:

Copy /ch/01/... to /ch/02/...

Or

Insert something on /ch/12/... and bump the former /ch/12/.. to /ch/13/... and all additional channels over one.

Edit: Actually, on further analysis this may be the way to go.

1
K900_•

You can write a helper function, something like this:

 def dictpath(value, path):
      for component in path:
           value = value[component]
      return value
3
freeallocOP•

This is:

a) annoyingly obvious :)

and

b) probably the way I'll go.

Thanks.

Edit: Actually I think this doesn't address my goal, but puts me on the right path. For my use, it needs to be something more like:

for p in path[1:]:
  if len(p) > 1:
    (recursively create key)
  else:
    (create key)
2
K900_•

Look into collections.defaultdict - it seems like just the thing you want for creating keys dynamically.

2
bheklilr•

You'll use a similar recursive algorithm to set values on this structure. I will also say that you can actually override indexing so you can build this structure then do things like

d['the', 'path', 'to', 'something']

Where the index being used is a tuple

Or even

d['/the/path/to/something']

Where the index is just split on your path separator then iterated over recursively.

1
forsakendaemon•

I've tried this and it's really difficult, predominately because of the "file or directory" problem.

I used a subclass of DefaultDict where the default value was an instance of that same class, that might be somewhere to start.

2
prashnts•

You can subclass dict:

class ndict(dict):
    def __getitem__(self, key):
        try:
            return super(ndict, self).__getitem__(key)
        except KeyError:
            self[key] = ndict()
            return self[key]

Then you can simply do:

>>> paths = ndict()
>>> paths['path']['to']['value'] = "memes"
{'path': {'to': {'value': 'memes'}}}
2
Brian•

Note that this is actually builtin as collections.defaultdict - you can do arbitrary depth just by having the default creation function return reference itself recursively..

Ie:

from collections import defaultdict

def variable_depth_dict():
    return defaultdict(variable_depth_dict)

paths = variable_depth_dict()

This creates a dictionary that defaults to a similar empty defaultdict for missing keys, so will work similarly to yours.

4