Jackyef
Jackyef

Reputation: 5012

Javascript Implementation of Python Dictionary

So, I just learnt about python's implementation of a hash-table, which is dictionary.

So here are what I understand so far, please correct me if I'm wrong:

  1. A dictionary is basically a structured data that contains key-value pairs.
  2. When we want to search for a key, we can directly call dict[key]. This is possible because python does a certain hash function on the key. The hash results is the index of the value in the dictionary. This way, we can get to the value directly after doing the hash function, instead of iterating through a list.
  3. Python will update the hash-table by increasing the amount of 'buckets' when the hash-table is filled 2/3rd of its maximum size.
  4. Python will always ensure that every 'buckets' will only have 1 entry in it so that the performance on lookup will be optimal, no iterations needed.

My first question is, am I understanding python dictionary correctly?

Second, does the javascript object also has all these 4 features? If not, is there another built-in javascript implementantion of dictionary/hash-table in general?

Upvotes: 1

Views: 135

Answers (1)

Brian S
Brian S

Reputation: 5056

JavaScript Objects can be used as dictionaries, but see Map for details on a JavaScript Map implementation. Some key takeaways are:

  • The Object prototype can potentially cause key collisions
  • Object keys can be Strings or Symbols. Map keys can be any value.
  • There is no direct means of determining how many "map" entries an Object has, whereas Map.prototype.size tells you exactly how many entries it has.

As a rule of thumb: if you're creating what is semantically a collection (an associative array), use a Map. If you've got different types of values to store, use an Object.

Upvotes: 1

Related Questions