0

次のようなタプルがあります。

(
    ('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
4

1 に答える 1