This question already has answers here:
How to add an element to the beginning of an OrderedDict?

(11个答案)


已关闭6年。




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

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

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

就我而言,我需要就地更新OrdedDict

背景

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

最佳答案

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

关于python - 插入到 “foo”键后面的OrderedDict中(原位),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29250479/

10-12 21:03