python - 在键 "foo"后面插入 OrderedDict(就地)

标签 python ordereddictionary

<分区>

我想在 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/

相关文章:

python - "How do I resolve the ' HTTP 403 : Forbidden ' error?"

python - 如何将 2 个数组列表添加到具有两个单独列名的单个 pandas 数据框中

python - 在命令行程序中创建 "Scrollable"输出

python - 有没有办法在 python 中获取所有大写和小写字母以及数字的列表?

python - OrderedDict 合并并追加 0(如果没有)

python - 如何获得书 "Web Scraping with Python: Collecting Data from the Modern Web"第 7 章数据标准化部分中的相同结果

c# - 没有 OrderedDictionary 的通用实现?

python - YUV420p转其他格式,色偏问题

python - 在 python 中使用有序字典作为对象字典

c# - 在括号列表中查找括号对 ()