Python:将多个嵌套列表组合成一个字典
我有一堆类似以下两个的列表:
['a', ['b', ['x', '1'], ['y', '2']]]
['a', ['c', ['xx', '4'], ['gg', ['m', '3']]]]
将所有这些列表组合成一个字典的最简单方法是什么,如下所示:
{'a': {
'b': {
'x':1,
'y':2
}
'c': {
'xx':4,
'gg': {
'm':3
}
}
}
嵌套的深度是可变的。
I have a bunch of lists like the following two:
['a', ['b', ['x', '1'], ['y', '2']]]
['a', ['c', ['xx', '4'], ['gg', ['m', '3']]]]
What is the easiest way to combine all of them into a single dictionary that looks like:
{'a': {
'b': {
'x':1,
'y':2
}
'c': {
'xx':4,
'gg': {
'm':3
}
}
}
The depth of nesting is variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个非常粗略的实现,它不处理奇怪的情况,例如少于两个元素的列表,并且它会覆盖重复的键,但它可以帮助您开始:
输出:
Here's a very crude implementation, it does not handle weird cases such as lists having less than two elements and it overwrites duplicate keys, but its' something to get you started:
Output:
这并不是真正的“Pythonic”,但我没有找到一种无需递归即可做到这一点的好方法
It's not really 'pythonic' but i dont see a good way to do this without recursion
对我来说,将这个问题分成两部分是最有意义的(好吧,我第一次通过......'S读错了这个问题)
转换
第一部分转换
[key, list1, list2] 数据结构嵌套字典:
要求
棘手的一点(至少对我来说)是意识到你必须从递归函数返回一个列表而不是字典。否则,您无法组合形成某些列表的第二个和第三个元素的并行列表。
为了使其更普遍有用(即对于元组和其他序列),我将更改为
You
can also make it work for any iterable 但这需要一点重组。
合并
第二部分合并在两个给定数据结构上运行第一个例程所产生的字典。我认为这将递归地合并任意数量的没有冲突键的字典,尽管除了这个用例之外我没有真正测试它。
It made the most sense to me to break this problem into two parts (well, that and I misread the question the first time through..'S)
transformation
The first part transforms the
[key, list1, list2]
data structure into nested dictionaries:It expects that
The tricky bit (at least for me) was realizing that you have to return a list from the recursive function rather than a dictionary. Otherwise, you can't combine the parallel lists that form the second and third elements of some of the lists.
To make this more generally useful (i.e. to tuples and other sequences), I would change
to
You can also make it work for any iterable but that requires a little bit of reorganization.
merging
The second part merges the dictionaries that result from running the first routine on the two given data structures. I think this will recursively merge any number of dictionaries that don't have conflicting keys, though I didn't really test it for anything other than this use case.