Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analogue of Python's OrderedDict?

Tags:

python

c#

.net

Is there a .net analogue of Python's OrderedDict?

An OrderedDict is a dictionary that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.

I want this precise behaviour.

like image 257
Colonel Panic Avatar asked Mar 01 '13 13:03

Colonel Panic


People also ask

What is an OrderedDict in Python?

Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.

Is OrderedDict obsolete?

No it won't become redundant in Python 3.7 because OrderedDict is not just a dict that retains insertion order, it also offers an order dependent method, OrderedDict. move_to_end() , and supports reversed() iteration*.

What is the difference between dict and OrderedDict?

The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.

Is OrderedDict slower than dict?

OrderedDict is over 80% slower than the standard Python dictionary (8.6/4.7≈1.83).


2 Answers

I believe System.Collections.Specialized.OrderedDictionary behaves like that.

like image 152
Pavel Anossov Avatar answered Sep 20 '22 14:09

Pavel Anossov


There is no generic implementation of OrderedDictionary collection in "vanilla" .NET, however, you still can write your own or use existing solutions:

OrderedDictionary: A generic implementation of IOrderedDictionary

like image 22
tyshka Avatar answered Sep 18 '22 14:09

tyshka