从键列表创建嵌套字典的方法 [英] Method for Creating a Nested Dictionary from a List of Keys
本文介绍了从键列表创建嵌套字典的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从保存键的任意元组/列表创建一个空的嵌套字典.我正在尝试找到一种在Python中执行此操作的简单方法.看起来应该由collection defaultdict处理,但我似乎无法弄清楚.
I would like to create an empty nested dictionary from an arbitrary tuple/list that holds the keys. I am trying to find a simple way to do this in Python. It looks like something that collections defaultdict should handle but I can't seem to figure it out.
keys = ('a', 'b', 'c')
还有一个字典,最终看起来像这样:
And a dictionary that will end up looking like this:
d = {
'a': {
'b': {
'c': {}
}
}
}
推荐答案
我想您可以使用reduce
做到这一点:
I suppose you could do it with reduce
:
def subdict(sub, key):
return { key: sub }
d = reduce(subdict, reversed(keys), {})
(在Python 3中,它是 functools.reduce
.)
(In Python 3, it’s functools.reduce
.)
这篇关于从键列表创建嵌套字典的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文