You can use reduce and reversed functions like this
>>> reduce(lambda res, cur: {cur: res}, reversed("foo/bar/baz".split("/")), 1) {'foo': {'bar': {'baz': 1}}}
If you are using Python 3.x, you need to import reduce from functools
>>> from functools import reduce >>> reduce(lambda res, cur: {cur: res}, reversed("foo/bar/baz".split("/")), 1) {'foo': {'bar': {'baz': 1}}}
Here, the last argument to reduce is the initial value. It will take values ββone by one from the iteration passed, call the function with the result and the current value, and then next time, the last result will be the first argument, and the current value will be the second argument. When the iterable is exhausted, it will return the result.
So, execution would be step by step as shown below
Let's say func is a lambda function, and it is called so many times
func(1, "baz") => {"baz": 1} func({"baz": 1}, "bar") => {"bar": {"baz": 1}} func({"bar": {"baz": 1}}, "foo") => {"foo": {"bar": {"baz": 1}}}
thefourtheye
source share