Home > other >  How to create a variable depth dictionary from a list or serie
How to create a variable depth dictionary from a list or serie

Time:10-22

I need to create a function that lets me create a dictionary with the items of lists (or series) with different length. Here's how I need it to work:

ex=[1,2,3,4]
unknownfunction(ex)
expected output: {1:{2:{3:4}}}

    
ex2=["a","b","c","d","e"]
unknownfunction(ex2)
expected output: {"a":{"b":{"c":{"d":"e"}}}}

Hope you can help me with this!

CodePudding user response:

Check this recursive function

def func(arr):
    if len(arr) == 1:
        return arr[0]
    return {arr[0]: func(arr[1: ])}

CodePudding user response:

For completeness, here's an iterative solution:

def makenest(seq):
    dct = seq[-1]
    for s in seq[-2::-1]:
        dct = { s: dct }
    return dct


ex=[1,2,3,4]
print(makenest(ex))
#expected output: {1:{2:{3:4}}}

ex2=["a","b","c","d","e"]
print(makenest(ex2))
#expected output: {"a":{"b":{"c":{"d":{"e"}}}}}

CodePudding user response:

Your 2 examples are a bit inconsistent (the second has the set {"e"} as a last element in contrast to the first one), so I am not sure what the precise specifications of this task are, but here is a solution for the first example:

from typing import List, Union, Dict

def unknownfunction(x: List[Union[int, float, str]]) -> Dict:
    assert len(x) >= 2, "List must have at least 2 elements"
    a = x.pop()
    b = x.pop()
    dic = {b:a}
    while x:
        c = x.pop()
        dic = {c: dic}
    return dic

CodePudding user response:

Here is my solution; it is yet again another take on this problem using some built in functions and taking advantage of Python's loose structure to create something that wouldn't normally been possible or seen in many other languages.

Now, I wouldn't necessarily advocate for this approach as it could cause some confusion changing a variable type within a loop but I just thought it was a neat showcase for what you can do in Python. Whether it is a good idea or not.

in stackoverflow.py:

def my_func(input: list) -> dict:
    output = input[len(input)-1]
    for index, item in enumerate(reversed(input)):
        if index == 0:
            continue

        output = {item: output}

    return output

In test_stackoverflow.py:

from stackoverflow import my_func


def test_my_func_works_with_numbers():
    res = my_func([1, 2, 3, 4])
    assert res == {1: {2: {3: 4}}}


def test_my_func_works_with_strings():
    res = my_func(["a", "b", "c", "d", "e"])
    assert res == {"a": {"b": {"c": {"d": "e"}}}}


def test_my_func_works_with_combination():
    res = my_func([1, "a", 3, "b"])
    assert res == {1: {"a": {3: "b"}}}


def test_my_func_works_with_only_one_entry():
    res = my_func([1])
    assert res == 1
  • Related