我有一个像这样的元组:
(
('Category 1', 40),
('Category 1 | Sub-Category 1', 20),
('Category 1 | Sub-Category 2', 20),
('Category 1 | Sub-Category 2 | Sub-Sub-Category 1', 5),
('Category 1 | Sub-Category 2 | Sub-Sub-Category 2', 15),
('Category 2', 20),
('Category 2 | Sub-Category 1', 15),
('Category 2 | Sub-Category 2', 5)
)
我想把它变成这样的字典:
^{pr2}$有任意数量的子类别。我很难想出一种Python式的方法来做这件事。有什么建议吗?在
编辑:如果其他人遇到这种问题并想要一个解决方案,下面是我(最终)想到的。我想作为一个答案,但不能,因为问题被关闭(叹息)。在
from itertools import groupby
def categoriesdict(value, depth=0):
categories = {}
for name, children in groupby(value, lambda c: c[0].split(' | ')[depth]):
# assumes that the first child is the group info
categories[name] = {
'count': children.next()[1],
'children': categoriesdict(children, depth + 1)
}
return categories
对于每个2元组,拆分第一个元组
[el.strip() for el in path.split('|')]
,然后按照该路径创建字典和子字典。在我会在几分钟内编辑一些代码。相关问题 更多 >
编程相关推荐