Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list into a dict where each key is nested under the next one

I want to convert this list:

[1,2,3,4,5]

Into this dict:

{ 1 :
  { 2 :
    { 3 :
      { 4 : 5 }}}}

This doesn't sound too complicated but I'm stumped when it's time to assign a value to a key deeper than the surface. I have a recursive function for finding how deep my dictionary goes but I don't know how to tell my algorithm to "add the new key here".

like image 629
MrPoulet Avatar asked Dec 31 '22 13:12

MrPoulet


1 Answers

You are looking for a recursive function that builds a dictionary with the first list element as a key and the transformed rest of the list as the value:

l = [1, 2, 3, 4, 5]

def l2d(l):  
    if len(l) < 2: # Not good
        raise Exception("The list is too short")
    if len(l) == 2: # Base case
        return {l[0]: l[1]}
    # Recursive case
    return {l[0]: l2d(l[1:])}

l2d(l)
# {1: {2: {3: {4: 5}}}}

Another interesting approach is to use functools.reduce:

from functools import reduce
reduce(lambda tail,head: {head: tail}, reversed(l))
# {1: {2: {3: {4: 5}}}}

It progressively applies a dictionary construction function to the first element of the list and the rest of it. The list is reversed first, so the construction naturally starts at the end. If the list is too short, the function returns its first element, which may or may not be desirable.

The "reduce" solution is MUCH FASTER, by about two orders of magnitude. The bottom line: avoid recursion.

like image 124
DYZ Avatar answered Jan 02 '23 04:01

DYZ