Home > Software engineering >  Python 3.x Convert nested list of elements into nested dictionary with max recursion
Python 3.x Convert nested list of elements into nested dictionary with max recursion

Time:08-24

I would like to convert a nested list like this:

["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]

to a nested dictionary like this:

{ "Pie": { "Sugar": {}, "Biscuit": { "Egg": {} } }, "Cocoa": {} }

with max recursion.

Possible variants of nested list:

["Pie", ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
["Pie", ["Sugar", ["Biscuit"], "Another something", ["Egg"], "Something", ["Something2"] ], "Cocoa", ["One", ["Nested1"], "Two", ["Nested2"] ]]

INCORRECT variants:

["Pie", [["Sugar"], "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]
[["Pie"], ["Sugar", "Biscuit", ["Egg"], "Something", ["Something2"] ], "Cocoa", []]

CodePudding user response:

Here is one approach (see comments in the code for details):

l = ["Pie", ["Sugar", "Biscuit", ["Egg"] ], "Cocoa", []]

def to_nested(l):
    out = {}
    skip = False
    for i, e in enumerate(l):  # enumerate to keep track of position
        if skip:  # we already used this item as value, skip it
            skip = False
            continue
        # ensure we have a next item and that it is a list
        if i 1<len(l) and isinstance(l[i 1], list):
            skip = True # flag item to be skipped as key
            out[e] = to_nested(l[i 1])
        else: # add a default empty dictionary as value
            out[e] = {}
    return out

out = to_nested(l)

output:

{'Pie': {'Sugar': {}, 'Biscuit': {'Egg': {}}}, 'Cocoa': {}}

CodePudding user response:

Simple approach with while loop and recursion. Hope it helps. I used pytest for quick testing.


import pytest

def convert(test):
    result = {}

    if not isinstance(test, list): 
        test = list(test)
    
    if len(test) == 1:
        return {test[0]:{}}
    
    i = 0
    
    while i < len(test):

        if not isinstance(test[i 1], list):
            result[test[i]] = {}
            i  = 1
            continue
        
        result[test[i]] = convert(test[i 1])
        i =2

    return result

example = [ 
    'Pie', [
        'Sugar', 
        'Biscuit', ['Egg'] 
        ],
     'Cocoa', [] 
    ]


wanted = { 
    "Pie": { 
        "Sugar": {}, 
        "Biscuit": { "Egg": {} } }, 
    "Cocoa": {} 
}

example_convertet = convert(example)


def test_simple_key_value():

    simple = ['hello', ['to you']]

    test_convert = convert(simple)

    assert test_convert == {
        'hello': {'to you':{}}
    }

def test_simple_key_with_multiple_values():

    simple = ['hello', ['to you', 'and you too', ['lol']]]

    test_convert = convert(simple)

    assert test_convert == {
        'hello' : {
            'to you': {}, 
            'and you too': {'lol':{}}}
    }

  • Related