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

时间:2019-05-20 13:44:16

标签: python django dictionary ordereddictionary

我在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))

它给了我

enter image description here

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

非常感谢您

1 个答案:

答案 0 :(得分:2)

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

像这样重新安排循环:

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))