【问题标题】:Turning a flat Python tuple into a nested dictionary?将平面 Python 元组变成嵌套字典?
【发布时间】:2013-09-08 13:51:37
【问题描述】:

我有一个如下所示的元组:

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

【问题讨论】:

  • 要求代码的问题必须表明对所解决问题的最低理解。包括尝试的解决方案、它们为什么不起作用以及预期的结果。另请参阅:堆栈溢出问题清单
  • 但是,我会提出一个建议:递归。
  • 由于有任意数量的子类别,我知道递归很可能是解决方案的一部分。到目前为止,我的尝试还没有奏效,也不完整。我稍后会发布我的尝试,我很抱歉最初没有发布它们,但否决票真的有必要吗?
  • 是的。目前这只是一个乞求代码。
  • 我的第一条评论不是我的原创。这是结束问题的既定标准之一。这里不欢迎简单地乞求代码而不发布您自己的尝试。

标签: python dictionary tuples itertools


【解决方案1】:

对于每个 2 元组,拆分第一个元组 [el.strip() for el in path.split('|')],然后按照该路径创建字典和子字典。

我会在几分钟内编辑一些代码。

d = {'count': 0, 'children': {}}
for (path, count) in els:
    path = [el.strip() for el in path.split('|')]
    here = d
    for el in path:
        print(el)
        if el not in here['children']:
            here['children'][el] = {'count': 0, 'children': {}}
        here = here['children'][el]
    here['count'] = count

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2020-07-29
    • 2019-11-14
    相关资源
    最近更新 更多