gpt4 book ai didi

python - 保持 OrderedDict 的顺序

转载 作者:行者123 更新时间:2023-12-01 08:29:16 25 4
gpt4 key购买 nike

我有一个 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”之前有“Genre”,这不是它在原始字典中的排序方式。我的错误似乎是什么?我该如何修复它?

最佳答案

如果没有完整的工作示例,很难准确说出问题所在。但根据您所显示的代码,我怀疑您的问题根本不在于 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而不是列表。

关于python - 保持 OrderedDict 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com