如何拆分字符串并形成多层嵌套字典? [英] How can I split a string and form a multi-level nested dictionary?

查看:87
本文介绍了如何拆分字符串并形成多层嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字符串

I have a string like

foo/bar/baz

例如,我也有val=1.是否有一种干净的方法可以将foo/bar/baz拆分为多维dict,使dict中的最后一项等于1.所以看起来像

I also have val=1 for example. Is there a clean way to split the foo/bar/baz into a multi-dimensional dict with the last item in the dict to equal 1. So it would look like

{'foo': {'bar': {'baz': 1}}}

推荐答案

您可以使用 reduce reversed 函数,例如这个

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}}}

如果您使用的是Python 3.x,则需要导入 reduce来自functools

If you are using Python 3.x, then 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}}}

在这里,reduce的最后一个参数是起始值.它将从传递的iterable中一个接一个地取值,并使用结果和当前值调用该函数,然后在下一次执行时,最后一个结果将是第一个参数,而当前值将是第二个参数.当迭代器用尽时,它将返回结果.

Here, the last argument to reduce is the starting value. It will take values one by one from the iterable passed, call the function with the result and the current value and then the next time onwards, the last result will be the first argument and the current value as the second argument. When the iterable is exhausted, it will return the result.

因此,执行将逐步进行,如下所示

So, the execution would have gone, step-by-step, as following

假设func是lambda函数,它会像这样反复调用

Let's say func is the lambda function and it gets repeatedly called like this

func(1, "baz")                   => {"baz": 1}
func({"baz": 1}, "bar")          => {"bar": {"baz": 1}}
func({"bar": {"baz": 1}}, "foo") => {"foo": {"bar": {"baz": 1}}}

这篇关于如何拆分字符串并形成多层嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆