Home Ask Login Register

Developers Planet

Your answer is one click away!

rocktheparty February 2016

How can I write my own OrderedDict class in Python?

Basically I want to understand how this thing works under the hood. I tried to create a list of tuples [(), (), ...] and each tuple will have two values, qst wuld be the key and second would be the value. but this is not a actual dictionary and also there is performance issue as well (I mean read/write/delete operations.

So How should I write a class MyOrderedDict which will (probably) be extending the default dict class.

any hint or resource would be appreciated.

PS: similar functional we have in Django. SortedDict

from django.utils.datastructures import SortedDict

are they both same or follow same approach in implementation?

Help on class SortedDict in module django.utils.datastructures:

class SortedDict(__builtin__.dict)
 |  A dictionary that keeps its keys in the order in which they're inserted.
 |  Method resolution order:
 |      SortedDict
 |      __builtin__.dict
 |      __builtin__.object
 |  Methods defined here:


Bluehorn February 2016

You might take a look at the source in Python 2. It seems that it is implemented in C for Python 3.

Aviah Laor February 2016

The class would manage a dictionary and a list. Behind the scenes, for every standard dict operation it will use both:

Dvalues = {"foo":"x","bar":"y","baz":"z"}
Lorder = ["bar","baz","foo"]

To get a value by key, as a standard dictionary:

return Dvalues[key]

To get a value by the order m it was entered:

return Dvalues[Lorder[m]]

Add key,value:

Dvalues[key] = value


Post Status

Asked in February 2016
Viewed 2,807 times
Voted 13
Answered 2 times


Leave an answer

Quote of the day: live life