【问题标题】:Keeping the order of an OrderedDict保持 OrderedDict 的顺序
【发布时间】:2018-12-31 22:29:18
【问题描述】:

我有一个要传递给函数的 OrderedDict。在函数的某个地方它改变了排序,虽然我不确定为什么并且正在尝试调试它。下面是函数以及函数和输出的例子:

def unnest_data(data):
    path_prefix = ''
    UNNESTED = OrderedDict()
    list_of_subdata = [(data, ''),] # (data, prefix)
    while list_of_subdata:
        for subdata, path_prefix in list_of_subdata:
            for key, value in subdata.items():
                path = (path_prefix + '.' + key).lstrip('.').replace('.[', '[')
                if not (isinstance(value, (list, dict))):
                    UNNESTED[path] = value
                elif isinstance(value, dict):
                    list_of_subdata.append((value, path))
                elif isinstance(value, list):
                    list_of_subdata.extend([(_, path) for _ in value])
            list_of_subdata.remove((subdata, path_prefix))
        if not list_of_subdata: break
    return UNNESTED

那么,如果我这样称呼它:

from collections import OrderedDict
data = OrderedDict([('Item', OrderedDict([('[@ID]', '288917'), ('Main', OrderedDict([('Platform', 'iTunes'), ('PlatformID', '353736518')])), ('Genres', OrderedDict([('Genre', [OrderedDict([('[@FacebookID]', '6003161475030'), ('Value', 'Comedy')]), OrderedDict([('[@FacebookID]', '6003172932634'), ('Value', 'TV-Show')])])]))]))])
unnest_data(data)                  

我得到的 OrderedDict 与我原来的排序不匹配:

OrderedDict([('Item[@ID]', '288917'), ('Item.Genres.Genre[@FacebookID]', ['6003172932634', '6003161475030']), ('Item.Genres. Genre.Value', ['TV-Show', 'Comedy']), ('Item.Main.Platform', 'iTunes'), ('Item.Main.PlatformID', '353736518')])

注意它是如何在“PlatformID”之前有“流派”的,这不是它在原始字典中的排序方式。我在这里的错误似乎是什么,我该如何解决?

【问题讨论】:

  • 如果一个键被完全删除然后放回,它将被移到最后。您可以通过将值设置为 None 或其他内容而不是删除它来避免这种情况。
  • @gilch 我已经删除了一些额外的代码并将其减少了一点,并且还减小了输入数据的大小。不幸的是,我不太确定如何进一步减少它,因为我首先不了解该错误或它发生的原因/位置。
  • @gilch 你指的是哪一行?

标签: python python-3.x recursion ordereddict


【解决方案1】:

如果没有完整的工作示例,很难准确地说出哪里出了问题。但是根据您显示的代码,我怀疑您的问题根本不在于OrderedDict,而是您在迭代list_of_subdata 时对其进行了修改,这将导致项目被意外跳过。

>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> for x in a:
...     print(x)
...     a.remove(x)
... 
1
3
5
7

考虑到您的使用情况,请考虑使用deque 而不是列表。

【讨论】:

    猜你喜欢
    • 2016-11-08
    • 2013-03-21
    • 2014-12-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2019-08-05
    • 2014-07-20
    相关资源
    最近更新 更多