【问题标题】:how to add an item to OrderedDict如何将项目添加到 OrderedDict
【发布时间】:2020-04-22 15:54:04
【问题描述】:

我有一个 OrderedDict,我需要在保持排序的同时添加一个元素

import sys
import bisect
from collections import OrderedDict

arr = {('a',1111),('b',2222),('f',3333)}
arr = OrderedDict(arr)

bisect.insort(arr,('c',4444))
#expectedly      arr = {('a',1111),('b',2222),('c',4444),('f',3333)}

#but actually     TypeError: collections.OrderedDict is not a sequence

更新:我需要按键排序存储的项目 但是有

import sys
import bisect
from collections import OrderedDict
from sortedcontainers import sorteddict
arr = {('a',1111),('b',2222),('f',3333)}
arr = OrderedDict(arr)
arr.update({'c':4444})   #or arr['c'] = 4444
print(arr)

OrderedDict([('b', 2222), ('f', 3333), ('a', 1111), ('c', 4444)])

而不是 OrderedDictх([('a',1111),('b',2222),('c',4444),('f',3333)])

类似于 c++ 中的地图

【问题讨论】:

  • arr['c'] = 4444 - arr 也是一组元组。
  • 另外,如果您使用的是 python3.7 及更高版本,dict 是默认排序的(在规范中)。您可以简单地做arr = dict((('a',1111),('b',2222),('f',3333))) 并通过插入获得有序字典
  • 因为您最初使用的是settuples,所以没有保证订单。见here。这意味着当您创建有序 dict 时,初始插入不会被排序。您应该改用listtuple
  • 为什么字典需要按键排序?您打算如何使用它?
  • @Alex 需要存储文本及其翻译并按文本排序

标签: python dictionary collections


【解决方案1】:

将新项目添加到原始项目,排序,制作新字典:

>>> arr = {('a',1111),('b',2222),('f',3333)}
>>> arr = collections.OrderedDict(arr)
>>> new = ('c',4444)
>>> items = list(arr.items())
>>> items.append(new)
>>> items.sort()
>>> arr = collections.OrderedDict(items)
>>> arr
OrderedDict([('a', 1111), ('b', 2222), ('c', 4444), ('f', 3333)])

或者更多的选择:

  • 子类 collections.OrderedDict
  • 使用move_to_end 方法作为指导,创建一个将遍历双向链表的新方法;找到插入的地方;然后插入新的密钥 - 也许可以在这里使用 bisect 或其他一些双向链表排序插入算法
  • 覆盖__setitem__ 方法并中调用新方法 - 或者用算法替换add-new-key-to-the-end代码您在上一个项目符号中提出的。

保持键排序顺序的排序字典

我不知道如何使 OrderedDict 子类工作 - 它有许多名称被破坏的属性 - 只需要重写一两个方法,我不想花时间弄清楚名称修饰方面。

所以只需将 整个 OrderedDict 类从源 from here - to here 复制到一个单独的模块中,这样您就可以导入它,并包含这些导入。

from _weakref import proxy as _proxy
from collections import _Link, _OrderedDictKeysView
from collections import _OrderedDictItemsView, _OrderedDictValuesView
import _collections_abc
from _weakref import proxy as _proxy
from reprlib import recursive_repr as _recursive_repr
from operator import itemgetter as _itemgetter, eq as _eq
import bisect

然后在类中更改以下内容:

  • 类名当然可以随便你。类名后面是一个文档字符串和一些描述类行为的 cmets - 这些应该更新。
    class SortOrderedDict(dict):
  • 覆盖__setitem__ 方法。下面使用bisect 查找插入顺序。不知道是否真的有必要,它必须首先列出一个 dict 键视图,但这部分应该是快速 C 代码(?在这里猜测)
    def __setitem__(self, key, value,
                    dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link in the linked list,
        # inserted at its key sorted position - uses less than comparisons,
        # and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            self.__map[key] = link = Link()
            root = self.__root
            last = root.prev
            link.key = key
            curr = root.next
            if curr is root:    # first item!
                link.prev, link.next = last, root
                last.next = link
                root.prev = proxy(link)
            elif link.key < root.next.key:    # at the beginning?
                #print(f'{link.key} before {root.next.key}')
                soft_link = root.next
                link.prev, link.next = root, soft_link
                soft_link.prev = link
                root.next = link
            elif root.prev.key < link.key:    # at the end?
                #print(f'{link.key} at the end after {root.prev.key}')
                soft_link = root.prev
                link.prev, link.next = soft_link, root
                soft_link.next = link
                root.prev = proxy(link)
            else:    # in the middle somewhere - use bisect
                keys = list(self.keys())
                i = bisect.bisect_left(keys,key)
                right = self.__map[keys[i]]
                #print(f'{link.key} between {right.prev.key} and {right.key}')
                soft_link = right.prev
                link.prev,link.next = soft_link,right
                right.prev = link
                soft_link.next = link

        dict_setitem(self, key, value)
  • 添加 update 方法 - 此类是 dict 的子类,这会覆盖其更新方法,强制其使用 __setitem__
    def update(self,other):
        try:
            other = other.items()
        except AttributeError:
            pass
        for k,v in other:
            self[k] = v
  • 将此行 update = __update = _collections_abc.MutableMapping.update 更改为
    __update = update
  • __reduce__ 方法中,将 for k in vars(OrderedDict()): 中的类名更改为您为类命名的任何名称
    for k in vars(SortOrderedDict()):
  • __eq__ 方法中的相同内容。将if isinstance(other, OrderedDict): 更改为
    if isinstance(other, SortOrderedDict):

如果使用 bisect 似乎不值得,只需遍历链表直到找到插入点。 (上面列出的所有其他更改仍然适用)

    def __setitem__(self, key, value,
                    dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
        'od.__setitem__(i, y) <==> od[i]=y'
        # Setting a new item creates a new link in the linked list,
        # inserted at its key sorted position - uses less than comparisons,
        # and the inherited dictionary is updated with the new key/value pair.
        if key not in self:
            self.__map[key] = link = Link()
            root = self.__root
            last = root.prev
            link.key = key
            curr = root.next
            if curr is root:    # first item!
                link.prev, link.next = last, root
                last.next = link
                root.prev = proxy(link)
            # traverse the linked list; find sorted insertion point; insert
            while curr is not root:
                if link.key < curr.key:
                    soft_link = curr.prev
                    soft_link.next = link
                    link.prev = soft_link
                    link.next = curr
                    curr.prev = link
                    break
                elif curr.next is root:
                    link.prev, link.next = curr, root
                    curr.next = link
                    root.prev = proxy(link)
                    break
                curr = curr.next
        dict_setitem(self, key, value)

用法

>>> arr = {('a',1111),('f',3333),('b',2222)}
>>> arr = SortOrderedDict(arr)
>>> arr
SortOrderedDict([('a', 1111), ('b', 2222), ('f', 3333)])
>>> other = {k:v for k,v in zip('tvsnpqkl',range(8))}
>>> arr.update(other)
>>> arr
SortOrderedDict([('a', 1111), ('b', 2222), ('f', 3333), ('k', 6), ('l', 7), ('n', 3), ('p', 4), ('q', 5), ('s', 2), ('t', 0), ('v', 1)])
>>> b = SortOrderedDict((('a',1111),('f',3333),('b',2222)))
>>> b.update(other)
>>> arr == b
True
>>> b == arr
True
>>> 

【讨论】:

  • 我需要不断地添加元素,而且每次排序都很昂贵
  • @Artem072 - 那么也许您应该在检索时专注于对它们进行排序? OrderedDict 仅维护插入顺序,因此要按排序顺序添加项目,您必须在每次 after 排序时创建一个新 dict。也许子类或 mixin 会起作用。
  • @Artem072 - 请参阅编辑以了解保持排序顺序的类。
【解决方案2】:

如果我理解正确,您希望字典按键排序:

from collections import OrderedDict

arr = {('a',1111),('b',2222),('f',3333)}
arr = OrderedDict(arr)
arr['c'] = 4444
arr = OrderedDict(x for x in sorted(arr.items()))

一个按排序键顺序迭代的python dict:

class SortedDict(dict):
    def __iter__(self):
        yield from sorted(super().__iter__())

    def items(self):
        yield from sorted(super().items())

x = SortedDict({'d': 0, 'c': 9, 'b': 1, 'a': 3})
for k in x:
    print(k)
# a
# b
# c
# d

【讨论】:

  • 我需要不断地添加元素,而且每次排序都很昂贵
  • 那么,相反,也许保留一份您可以保持排序的密钥副本并使用它来访问字典? OrderedDict 只跟踪插入顺序。
  • @Artem072 我写了一个扩展 dict 的小例子,它可以按任何顺序排列,但在循环时会排序。
  • @Artem072 还有 sortedcontainers 这些可能更快,因为它们是用 C 编写的
猜你喜欢
  • 2013-05-15
  • 2012-01-05
  • 2019-04-11
  • 1970-01-01
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多