Skip to content

Instantly share code, notes, and snippets.

@jaredks
Last active May 23, 2019 06:42
Show Gist options
  • Save jaredks/6276032 to your computer and use it in GitHub Desktop.
Save jaredks/6276032 to your computer and use it in GitHub Desktop.
OrderedDict subclass implementing insertion methods to adjust the order.
from collections import OrderedDict as _OrderedDict
try:
from thread import get_ident as _get_ident
except ImportError:
from dummy_thread import get_ident as _get_ident
class ListDict(_OrderedDict):
def __init__(self, *args, **kwds):
try:
self.__insertions_running
except AttributeError:
self.__insertions_running = {}
super(ListDict, self).__init__(*args, **kwds)
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
if _get_ident() in self.__insertions_running:
self.__insertions_running[_get_ident()] = key, value
else:
super(ListDict, self).__setitem__(key, value, dict_setitem)
def __insertion(self, link_prev, key_value):
self.__insertions_running[_get_ident()] = 1
self.__setitem__(*key_value)
key, value = self.__insertions_running.pop(_get_ident())
if link_prev[2] != key:
if key in self:
del self[key]
link_next = link_prev[1]
self._OrderedDict__map[key] = link_prev[1] = link_next[0] = [link_prev, link_next, key]
dict.__setitem__(self, key, value)
def insert_after(self, existing_key, key_value):
self.__insertion(self._OrderedDict__map[existing_key], key_value)
def insert_before(self, existing_key, key_value):
self.__insertion(self._OrderedDict__map[existing_key][0], key_value)
from collections import OrderedDict as _OrderedDict
class ListDict(_OrderedDict):
def __insertion(self, link_prev, key_value):
key, value = key_value
if link_prev[2] != key:
if key in self:
del self[key]
link_next = link_prev[1]
self._OrderedDict__map[key] = link_prev[1] = link_next[0] = [link_prev, link_next, key]
dict.__setitem__(self, key, value)
def insert_after(self, existing_key, key_value):
self.__insertion(self._OrderedDict__map[existing_key], key_value)
def insert_before(self, existing_key, key_value):
self.__insertion(self._OrderedDict__map[existing_key][0], key_value)
@Divyendra
Copy link

Good attempt but regretfully would not work in Python3.5. The OrderedDict implementation is in C in 3.5 which would not allow to inherit '_map' attribute. In case we want to circumvent this, can forcefully use python implementation:

py_coll = import_fresh_module('collections', blocked=['_collections'])
OrderedDict = py_coll.OrderedDict

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment