如何更改dict的索引值?

发布于 01-19 22:59 字数 599 浏览 2 评论 0原文

是否可以更改已排序字典的值?

按字母顺序对字典进行排序后,我得到了这样的结果:

OrderedDict([('a', {'index': 3, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 4, 'parent': 'a/b'}),
             ('a/b/d', {'index': 1, 'parent': 'a/b'})])

这个字典有更多这样的键/值对,我的预期输出是保持它按字母顺序排序,但更改索引值,使其看起来像这样:

OrderedDict([('a', {'index': 1, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 3, 'parent': 'a/b'}),
             ('a/b/d', {'index': 4, 'parent': 'a/b'})])

我该怎么做那?

Is it possible to change the values of a sorted dictionary?

After sorting the dict alphabetically I got a result like this:

OrderedDict([('a', {'index': 3, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 4, 'parent': 'a/b'}),
             ('a/b/d', {'index': 1, 'parent': 'a/b'})])

This dict has a bunch more of key/value pairs like that, my expected output is to maintain it sorted alphabetically but change the indexes value so it looks like this:

OrderedDict([('a', {'index': 1, 'parent': None}),
             ('a/b', {'index': 2, 'parent': 'a'}),
             ('a/b/c', {'index': 3, 'parent': 'a/b'}),
             ('a/b/d', {'index': 4, 'parent': 'a/b'})])

How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

话少情深2025-01-26 22:59:07

迭代字典的值并设置每个值的索引

for i, value in enumerate(dct.values(), start=1):
    value['index'] = i

Iterate over the dictionary's values and set each value's index:

for i, value in enumerate(dct.values(), start=1):
    value['index'] = i
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文