简体   繁体   中英

Generate tree from Python list of list

I have the following Python list:

[
  ['a.b.c.d.e.rollover', 0],
  ['a.b.c.d.e.f.rollover', 1],
  ['a.b.c.d.e.g.rollover', 0]
]

Suppose this list is extremely large (lots of elements !)

Is there an efficient way in Python to convert this into a multi-level dictionary like the following ?

{
  'a': {
     'b': {
        'c': {
           'd': {
              'e': {
                 'rollover': 0,
                 'f': {
                    'rollover': 1
                 }
                 'g': {
                    'rollover': 0
                 }
              }
            }
          }
        }
      }
    }
  }
}

You can utilize defaultdict with lambda that returns defaultdict that uses the same lambda :

from collections import defaultdict

l = [
  ['a.b.c.d.e.rollover', 0],
  ['a.b.c.d.e.f.rollover', 1],
  ['a.b.c.d.e.g.rollover', 0]
]

dd = lambda: defaultdict(dd)
res = dd()

for k, v in l:
    d = res
    keys = k.split('.')

    # Add all the keys except the last one, d[x] will do since 
    # it forces default value to be generated
    for x in keys[:-1]:
        d = d[x]

    # Assign value to last key
    d[keys[-1]] = v

print res['a']['b']['c']['d']['e']['rollover'] # 0
print res['a']['b']['c']['d']['e']['f']['rollover'] # 1

Short explanation: In order to automatically generate a new defaultdict in case that key doesn't exist we need a function (or lambda ) that returns such an object. Since defaultdict constructor needs a parameter we have to provide a function that passes the parameter to defaultdict . Every time that non-existing key is being dereferenced the function is called and it creates a new defaultdict that will again call the same function in the future if required. This is called autovivification .

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