从 Python 中的 OrderedDict 访问数据并对其进行循环

Access to data from OrderedDict in Python and loop over it

我的 Django 应用程序中有一个 OrderedDict,它可以为每个版本获取 content editioncontent subversions

看起来像这样:

from collections import OrderedDict
od = OrderedDict()

for version in list_of_edition():
    od.setdefault((version.pk, version.title), []).extend([(subversion.pk, subversion.title) for subversion in version.collection.all()])

我得到:

OrderedDict([((2, '10th Edition (Current)'), [(58464, 'Ph. Eur. 10.0 lite')]), ((1, '9th Edition'), [(21928, 'Ph. Eur. 9.8 lite'), (29235, 'Ph. Eur. 9.9 lite'), (36542, 'Ph. Eur. 9.10 lite')])])

# Rewritten in order to get more readable
OrderedDict(
    [
        (
            (2, '10th Edition (Current)', True), [(58464, 'Ph. Eur. 10.0 lite')]
        ),
        (
            (1, '9th Edition', True), [(21928, 'Ph. Eur. 9.8 lite'), (29235, 'Ph. Eur. 9.9 lite'), (36542, 'Ph. Eur. 9.10 lite')]
        )
    ]
)

这个 OrderedDict 让我可以在导航栏菜单中创建用于导航的选项卡。 应该是:

Tab : 10th Edition (Current) 
    |
    ---> subtab : Ph. Eur. 10.0 lite

Tab : 9th Edition
    |
    ---> subtab : Ph. Eur. 9.8 lite
    |
    ---> subtab : Ph. Eur. 9.9 lite
    |
    ---> subtab : Ph. Eur. 9.10 lite

在我的menu.py文件中,菜单是这样创建的:

content_children = (
    AdminMenuItem(_('Manage smth1'), reverse('smth1-list'), weight=100, separator=False),
    AdminMenuItem(_('Manage smth2'), reverse('smth2-list'), weight=100, separator=False),
    ...
)

Menu.add_item('content', MenuItem(_('Content'), '#content', children=content_children)

所以我试图循环遍历 OrderedDict,以便像前面的示例一样创建我的菜单。我在隔离每个菜单并为每个关联的菜单添加子菜单时遇到了一些困难:

edition_children = ()
for version in od:
    for element in od[version]:
        edition_children += MenuItem(element[1], reverse('home'), weight=150, separator=False),

for version in od:
    Menu.add_item('edition', MenuItem(version[1], '#', children=edition_children))

它给了我:

9th Edition也是一样。对于 10th Edition,我应该只有 Ph. Eur. 10.x,对于 9th Edition,我应该只有 Ph. Eur. 9.x

非常感谢您提前

您正在构建所有 sub-versions 的列表,然后将该列表添加到所有版本。

Re-arrange 你的循环是这样的:

for version in od:
    edition_children = ()
    for element in od[version]:
        edition_children += MenuItem(element[1], reverse('home'), weight=150, separator=False),
    Menu.add_item('edition', MenuItem(version[1], '#', children=edition_children))