Delete a key and value from an OrderedDict

Yes, you can use del: del dct[key] Below is a demonstration: >>> from collections import OrderedDict >>> dct = OrderedDict() >>> dct[‘a’] = 1 >>> dct[‘b’] = 2 >>> dct[‘c’] = 3 >>> dct OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3)]) >>> del dct[‘b’] >>> dct OrderedDict([(‘a’, 1), (‘c’, 3)]) >>> In fact, you should always … Read more

Override the {…} notation so i get an OrderedDict() instead of a dict()?

Here’s a hack that almost gives you the syntax you want: class _OrderedDictMaker(object): def __getitem__(self, keys): if not isinstance(keys, tuple): keys = (keys,) assert all(isinstance(key, slice) for key in keys) return OrderedDict([(k.start, k.stop) for k in keys]) ordereddict = _OrderedDictMaker() from nastyhacks import ordereddict menu = ordereddict[ “about” : “about”, “login” : “login”, ‘signup’: “signup” … Read more

How to sort OrderedDict of OrderedDict?

You’ll have to create a new one since OrderedDict is sorted by insertion order. In your case the code would look like this: foo = OrderedDict(sorted(foo.items(), key=lambda x: x[1][‘depth’])) See http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes for more examples. Note for Python 2 you will need to use .iteritems() instead of .items().

OrderedDictionary and Dictionary

You are doing it wrong. You need not only to insert values sequentially into dictionary, but also remove some elements and see how the order has changed after this. The next code demonstrates this: OrderedDictionary od = new OrderedDictionary(); Dictionary<String, String> d = new Dictionary<String, String>(); Random r = new Random(); for (int i = … Read more

Last element in OrderedDict

Using next(reversed(od)) is a perfect way of accessing the most-recently added element. The class OrderedDict uses a doubly linked list for the dictionary items and implements __reversed__(), so this implementation gives you O(1) access to the desired element. Whether it is worthwhile to subclass OrderedDict() for this simple operation may be questioned, but there’s nothing … Read more

Any way to properly pretty-print OrderedDict?

Ever since Python 3.7, Python guarantees that keys in a dictionary will retain their insertion order. (They still don’t behave exactly the same as OrderedDict objects, though, as two dicts a and b can be considered equal a == b even if the order of the keys is different, whereas OrderedDict does check this upon … Read more