Are there any dictionaries in javascript like python?

I need to make a dictionary in javascript like this

I donโ€™t remember the exact notation, but it was something like:

states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ } 

Is there such a thing in javascript?

+78
javascript python
Aug 24 '10 at 17:15
source share
7 answers

This is an old post, but I still decided to give an illustrated answer.

Use javascript object notation. Like this:

 states_dictionary={ "CT":["alex","harry"], "AK":["liza","alex"], "TX":["fred", "harry"] }; 

And to access the values:

 states_dictionary.AK[0] //which is liza 

or you can use the letter designation of the javascript object, and the keys do not have to be in quotation marks:

 states_dictionary={ CT:["alex","harry"], AK:["liza","alex"], TX:["fred", "harry"] }; 
+101
Aug 03
source share

Javascript has no real associative arrays. You can try using objects:

 var x = new Object(); x["Key"] = "Value"; 

However, it is not possible to use typical array properties or methods of type array.length with objects. At the very least, you can access the "array object" in an inline loop.

+45
Aug 24 '10 at 17:26
source share

Created a simple dictionary in JS here:

 function JSdict() { this.Keys = []; this.Values = []; } // Check if dictionary extensions aren't implemented yet. // Returns value of a key if (!JSdict.prototype.getVal) { JSdict.prototype.getVal = function (key) { if (key == null) { return "Key cannot be null"; } for (var i = 0; i < this.Keys.length; i++) { if (this.Keys[i] == key) { return this.Values[i]; } } return "Key not found!"; } } // Check if dictionary extensions aren't implemented yet. // Updates value of a key if (!JSdict.prototype.update) { JSdict.prototype.update = function (key, val) { if (key == null || val == null) { return "Key or Value cannot be null"; } // Verify dict integrity before each operation if (keysLength != valsLength) { return "Dictionary inconsistent. Keys length don't match values!"; } var keysLength = this.Keys.length; var valsLength = this.Values.length; var flag = false; for (var i = 0; i < keysLength; i++) { if (this.Keys[i] == key) { this.Values[i] = val; flag = true; break; } } if (!flag) { return "Key does not exist"; } } } // Check if dictionary extensions aren't implemented yet. // Adds a unique key value pair if (!JSdict.prototype.add) { JSdict.prototype.add = function (key, val) { // Allow only strings or numbers as keys if (typeof (key) == "number" || typeof (key) == "string") { if (key == null || val == null) { return "Key or Value cannot be null"; } if (keysLength != valsLength) { return "Dictionary inconsistent. Keys length don't match values!"; } var keysLength = this.Keys.length; var valsLength = this.Values.length; for (var i = 0; i < keysLength; i++) { if (this.Keys[i] == key) { return "Duplicate keys not allowed!"; } } this.Keys.push(key); this.Values.push(val); } else { return "Only number or string can be key!"; } } } // Check if dictionary extensions aren't implemented yet. // Removes a key value pair if (!JSdict.prototype.remove) { JSdict.prototype.remove = function (key) { if (key == null) { return "Key cannot be null"; } if (keysLength != valsLength) { return "Dictionary inconsistent. Keys length don't match values!"; } var keysLength = this.Keys.length; var valsLength = this.Values.length; var flag = false; for (var i = 0; i < keysLength; i++) { if (this.Keys[i] == key) { this.Keys.shift(key); this.Values.shift(this.Values[i]); flag = true; break; } } if (!flag) { return "Key does not exist"; } } } 

The above implementation can now be used to simulate a dictionary like:

 var dict = new JSdict(); dict.add(1, "one") dict.add(1, "one more") "Duplicate keys not allowed!" dict.getVal(1) "one" dict.update(1, "onne") dict.getVal(1) "onne" dict.remove(1) dict.getVal(1) "Key not found!" 

This is just basic modeling. It can be further optimized by implementing a more efficient runtime algorithm for working at least in O (nlogn) time complexity or even less. Like merge / quick sort on arrays, and then some B-lookup to search. I have not tried or searched for the mapping of the hash function in JS.

In addition, the key and value for the JSdict obj object can be turned into private variables to be mean.

Hope this helps!

EDIT โ†’ After doing the above, I personally used JS objects as associative arrays that are accessible from the box.

However, I would especially like to mention two methods that actually turned out to be useful for the convenience of using a hash table.

Viz: dict.hasOwnProperty (key) and delete dict [key]

Read this post as a good resource on this implementation / use. Dynamically create keys in an associative JavaScript array

THANKS!

+9
Aug 30 '13 at 14:10
source share

I understand that this is an old question, but it appears on Google when you search for javascript dictionaries, so I would like to add to the answers above that in ECMAScript 6 the official Map object, which is the implementation of the dictionary:

 var dict = new Map(); dict.set("foo", "bar"); //returns "bar" dict.get("foo"); 

Unlike regular javascript objects, it allows any object as a key:

 var foo = {}; var bar = {}; var dict = new Map(); dict.set(foo, "Foo"); dict.set(bar, "Bar"); //returns "Bar" dict.get(bar); //returns "Foo" dict.get(foo); //returns undefined, as {} !== foo and {} !== bar dict.get({}); 
+9
Oct 07 '15 at 13:38
source share

Use JavaScript objects. You can access your properties, such as keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org

+4
Aug 24 '10 at 17:18
source share

An old question, but I recently needed to make AS3> JS port, and for speed I wrote a simple AS3 dictionary object for JS:

http://jsfiddle.net/MickMalone1983/VEpFf/2/

If you do not know, the AS3 dictionary allows you to use any object as a key, not just a string. They are very convenient if you find them useful.

It is not as fast as a native object can be, but in this respect I did not find any serious problems.

API:

 //Constructor var dict = new Dict(overwrite:Boolean); //If overwrite, allows over-writing of duplicate keys, //otherwise, will not add duplicate keys to dictionary. dict.put(key, value);//Add a pair dict.get(key);//Get value from key dict.remove(key);//Remove pair by key dict.clearAll(value);//Remove all pairs with this value dict.iterate(function(key, value){//Send all pairs as arguments to this function: console.log(key+' is key for '+value); }); dict.get(key);//Get value from key 
+3
Mar 24 '13 at 16:03
source share

Firefox 13+ provides an experimental implementation of the map object, similar to the dict object in python. Specifications here .

It is available only in firefox, but it looks better than when using the new Object() attributes. Quoting from the documentation:

  • The object has a prototype, so there are default keys on the map. However, this can be circumvented using map = Object.create(null) .
  • The Object key is Strings , where they can be any value for map .
  • You can easily get the size of the map , while you need to manually track the size for the Object .
+1
Jun 24 '13 at 1:13
source share



All Articles