我有一个看起来像这样的元组:
(
('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)
)
我想把它变成一个看起来像这样的字典:
{
'Category 1': {
'count': 40,
'children': {
'Sub-Category 1': {'count': 20, 'children': []},
'Sub-Category 2': {
'count': 20,
'children': {
'Sub-Sub-Category 1': {'count': 5, 'children': []},
'Sub-Sub-Category 2': {'count': 15, 'children': []}
}
}
}
},
'Category 2': {
'count': 20,
'children': {
'Sub-Category 1': {'count': 15, 'children': []},
'Sub-Category 2': {'count': 5, 'children': []},
}
}
}
有任意数量的子类别。我很难考虑用 Pythonic 的方式来做这件事。有什么建议么?
编辑:如果其他人遇到这种问题并想要解决方案,这就是我(最终)想出的。我会发布作为答案,但由于问题已关闭(叹息),我不能。
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