1

I would like to create an empty nested dictionary from an arbitrary tuple/list that holds the keys. I am trying to find a simple way to do this in Python. It looks like something that collections defaultdict should handle but I can't seem to figure it out.

keys = ('a', 'b', 'c')

And a dictionary that will end up looking like this:

d = {
    'a': {
          'b': {
                'c': {}
               }
          }
     }
Randy
  • 908
  • 12
  • 30
  • Is the dict supposed to have an entry for keys that weren't in the tuple? If not, `defaultdict` probably isn't the way to go. If so, check out this brilliant recursive `defaultdict` constructor: http://stackoverflow.com/questions/19189274/defaultdict-of-defaultdict-nested – Peter DeGlopper Dec 04 '13 at 22:15
  • That is brilliant, but I don't want to do something like `d[a][b][c]` to create it, I would like to do it as a one-liner comprehension since there will be an arbitrary # of keys. – Randy Dec 04 '13 at 22:20
  • I expect there is a one-liner that would prepopulate the recursive `defaultdict` so that calls like `keys` would work as you expect - the real question is whether the `defaultdict` behavior of returning something for `d['foobar']` is what you want or not. – Peter DeGlopper Dec 04 '13 at 22:23

2 Answers2

6

I suppose you could do it with reduce:

def subdict(sub, key):
    return { key: sub }

d = reduce(subdict, reversed(keys), {})

(In Python 3, it’s functools.reduce.)

Ry-
  • 218,210
  • 55
  • 464
  • 476
0
def nested_dict(keys):
      if len(keys) == 1:
           return {keys[0]: {}}
      return {keys[0]: nested_dict(keys[1:])}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437