简体   繁体   中英

Method for Creating a Nested Dictionary from a List of Keys

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': {}
               }
          }
     }

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 .)

def nested_dict(keys):
      if len(keys) == 1:
           return {keys[0]: {}}
      return {keys[0]: nested_dict(keys[1:])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM