在“foo”键后面插入已订购的信息技术(就地)

2024-09-25 08:39:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在OrdedDict中的给定键后面插入一个键。

示例:

my_orderded_dict=OrderedDict([('one', 1), ('three', 3)])

我想'two' --> 2进入正确的位置。

在我的例子中,我需要在适当的地方更新OrdedDict

背景

Django的SortedDict(具有insert())被移除:https://code.djangoproject.com/wiki/SortedDict


Tags: django示例my地方onedict例子ordereddict
1条回答
网友
1楼 · 发布于 2024-09-25 08:39:05
from collections import OrderedDict # SortedDict of Django gets removed: https://code.djangoproject.com/wiki/SortedDict

my_orderded_dict=OrderedDict([('one', 1), ('three', 3)])

new_orderded_dict=my_orderded_dict.__class__()
for key, value in my_orderded_dict.items():
    new_orderded_dict[key]=value
    if key=='one':
        new_orderded_dict['two']=2
my_orderded_dict.clear()
my_orderded_dict.update(new_orderded_dict)
print my_orderded_dict

相关问题 更多 >