tags:

views:

257

answers:

4

LinkedHashMap is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked list maintaining the insertion order.

Is there an equivalent to that in Python?

+7  A: 

Although you can do the same thing by maintaining a list to keep track of insertion order, python 3.1 has an OrderedDict class in its collections module.

Before python 3.1, you can subclass dict, and have an extra list data member that stores the keys in the order they were inserted. You can implement __getitem__, __setitem__ and __iter__ etc to get this done.

sykora
The OrderedDict is coming in Python 3.1, but is not yet in 3.0, according to the documentation you linked.
kquinn
Yes, you're right, I had overlooked that. Edited.
sykora
+1  A: 

I don't think so; you'd have to use a dict plus a list. But you could pretty easily wrap that in a class, and define keys, __getitem__, __setitem__, etc. to make it work the way you want.

DNS
+1  A: 

I am not sure whether this is what you are asking for:

>>> dic = {1: 'one', 2: 'two'}
>>> for k, v in dic.iteritems():
...     print k, v

you can order the dic in the order of the insertion using ordereddict module.

d = ordereddict(dic, relax=True)
aatifh
I don't think ``dict.iteritems`` provides an ordering based on the order of insertion...
sykora
Correct! You have to use ordereddict module for that.
aatifh
+3  A: 

This answer to the question How do you retrieve items from a dictionary in the order that they’re inserted? contains an implementation of an ordered dict, in case you're not using Python 3.x and don't want to give yourself a dependency on the third-party ordereddict module.

Eli Courtwright
The ordered_dict class is exactly what I have searched for. Thx.
dmeister