Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent for LinkedHashMap in Python

Tags:

python

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?

like image 970
dmeister Avatar asked Mar 17 '09 11:03

dmeister


People also ask

What is LinkedHashMap in Python?

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 a HashMap in Python?

Hashmaps or Hash Tables in Python are implemented via the built-in data type. The keys of the built-in data type are generated with the help of a hashing function.

Is dictionary in Python same as HashMap?

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

How HashMap works internally in Python?

Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index.


2 Answers

If you're on Python 2.7 or Python >=3.1 you can use collections.OrderedDict in the standard library.

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.

like image 78
Eli Courtwright Avatar answered Oct 20 '22 16:10

Eli Courtwright


Although you can do the same thing by maintaining a list to keep track of insertion order, Python 2.7 and Python >=3.1 have an OrderedDict class in the collections module.

Before 2.7, you can subclass dict following this recipe.

like image 29
sykora Avatar answered Oct 20 '22 18:10

sykora