0
votes

I need to generate a dictionary like this:

{
  'newEnv': {
     'newProj': {
        'newComp': {
           'instances': [],
           'n_thing': 'newThing'
        }
     }
  }
}

from a tuple, like this: ('newEnv','newProj','newComp','newThing') but only if that doesn't already exists. So, I tried this:

myDict = {}
(env,proj,comp,thing) = ('newEnv','newProj','newComp','newThing')

if env not in myDict:
    myDict[env] = {}
if proj not in myDict[env]:
    myDict[env][proj] = {}
if comp not in myDict[env][proj]:
    myDict[env][proj][comp] = {'n_thing': thing, 'instances': []}

which is pretty much working but not sure how efficient is that or if I should be doing this way at all. Any suggestion(s)??

2
By the way, your solution is not bad by any means. - aIKid

2 Answers

6
votes

You can use a loop (with just the first 3 keys, newThing is not a key in the chain):

myDict = {}
path = ('newEnv','newProj','newComp')
current = myDict
for key in path:
    current = current.setdefault(key, {})

where current ends up as the innermost dictionary, letting you set the 'n_thing' and 'instances' keys on that.

You could use reduce() to collapse that into a one-liner:

myDict = {}
path = ('newEnv','newProj','newComp')
reduce(lambda d, k: d.setdefault(k, {}), path, myDict)

The reduce call returns the innermost dictionary, so you can use that to assign your final value:

myDict = {}
path = ('newEnv','newProj','newComp')
inner = reduce(lambda d, k: d.setdefault(k, {}), path, myDict)
inner.update({'n_thing': 'newThing', 'instances': []})
0
votes

you can do something similar, maybe slightly simpler, with a defaultdict of defaultdicts (see defaultdict of defaultdict, nested for some discussion)

tree = lambda: defaultdict(tree)

base = tree()
for x in mytuple[:-2]:
    base = base[x]
base[x] = mytuple[-1]

which is very similar to martijn's, just using the default functionality to create the subdicts instead of doing it directly with setdefault.

this also lets you type directly

myDict[env][proj][comp].setdefault('instances', list()).append(queue)

if that's what you are really looking for. (there's no way to remove the setdefault unfortunately; after all, I don't know ahead of time whether you want a list or dict. you only have one default)....