Skip to content Skip to sidebar Skip to footer

Convert A List Of Delimited Strings To A Tree/nested Dict, Using Python

I am trying to convert a list of dot-separated strings, e.g. ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero'] into a tree (nested lists or dicts - any

Solution 1:

ls = ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero']
tree = {}

for item inls:
    t = tree
    for part in item.split('.'):
        t = t.setdefault(part, {})

Result:

{"twelve":{"zero":{}},"five":{"nine":{"ten":{}}},"one":{"six":{"seven":{"eight":{}}},"two":{"three":{"four":{}}}}}

Solution 2:

While this is beyond the reach of the original question, some comments mentioned a form of this algorithm that incorporates values. I came up with this to that end:

defdictionaryafy(self, in_dict):
    tree = {}
    for key, value in in_dict.items():
        t = tree
        parts = key.split(".")
        for part in parts[:-1]:
            t = t.setdefault(part, {})
        t[parts[-1]] = value
    return tree

Post a Comment for "Convert A List Of Delimited Strings To A Tree/nested Dict, Using Python"