Comparison of programming languages (associative array): Difference between revisions

Content deleted Content added
m F#: {{code}}
 
(36 intermediate revisions by 22 users not shown)
Line 2:
{{TOC limit|3}}
 
This '''Comparisoncomparison of programming languages (associative arrays)''' compares the features of [[associative array]] [[data structure]]s or array-lookup processing for over 40 computer [[programming language]]s.
 
==Language support==
Line 8:
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
 
===AwkAWK===
[[AwkAWK]] has built-in, language-level support for associative arrays.
 
For example:
 
<syntaxhighlight lang="awk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
Line 29:
The user can search for elements in an associative array, and delete elements from the array.
 
The following shows how multi-dimensional associative arrays can be simulated in standard AwkAWK using concatenation and the built-in string-separator variable SUBSEP:
 
<syntaxhighlight lang=awk>
Line 47:
There is no standard implementation of associative arrays in [[C (programming language)|C]], but a 3rd-party library, C Hash Table, with BSD license, is available.<ref>[https://web.archive.org/web/20071015024120/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], archived [https://web.archive.org/web/20040902160534/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], with the source code available [https://github.com/davidar/c-hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code></ref>
 
Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key.<ref>{{cite web |title=uthash: a hash table for C structures |url=httphttps://uthash.sourceforge.net/ |website=Github |access-date=3 August 2020}}</ref>
 
Finally, the [[GLib]] library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.<ref>{{cite web |title=Hash Tables |url=https://developer.gnome.org/glib/stable/glib-Hash-Tables.html |website=Gnome Developer |access-date=3 August 2020}}</ref>
Line 63:
* assigning to the backing property of the indexer, for which the indexer is [[syntactic sugar]] (not applicable to C#, see [[#F#|F#]] or [[#Visual Basic .NET|VB.NET]] examples).
 
<syntaxhighlight lang=CSharp"csharp">
Dictionary<string,var string> dicdictionary = new Dictionary<string, string>();
dicdictionary.Add("Sally Smart", "555-9999");
dicdictionary["John Doe"] = "555-1212";
// Not allowed in C#.
// dicdictionary.Item("J. Random Hacker") = "553-1337";
dicdictionary["J. Random Hacker"] = "553-1337";
</syntaxhighlight>
 
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to <code>Add</code>.
 
<syntaxhighlight lang=CSharp"csharp">
var dicdictionary = new Dictionary<string, string> {
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
Line 85:
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and the <code>TryGetValue</code> method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
 
<syntaxhighlight lang=CSharp"csharp">
var sallyNumber = dicdictionary["Sally Smart"];
</syntaxhighlight>
<syntaxhighlight lang=CSharp"csharp">
var sallyNumber = (dicdictionary.TryGetValue("Sally Smart", out var result) ? result : "n/a";
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
Line 97:
 
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang=CSharp"csharp">
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in dicdictionary)
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
Line 108:
[[C++]] has a form of associative array called [[map (C++)|<code>std::map</code>]] (see [[Standard Template Library#Containers]]). One could create a phone-book map with the following code in C++:
 
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 122:
 
Or less efficiently, as this creates temporary <code>std::string</code> values:
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 136:
With the extension of [[C++11#Initializer lists|initialization lists]] in C++11, entries can be added during a map's construction as shown below:
 
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 151:
You can iterate through the list with the following code (C++03):
 
<syntaxhighlight lang=Cpp"cpp">
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
Line 159:
The same task in C++11:
 
<syntaxhighlight lang=Cpp"cpp">
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Line 166:
Using the structured binding available in [[C++17]]:
 
<syntaxhighlight lang=Cpp"cpp">
for (const auto& [name, number] : phone_book) {
std::cout << name << " = " << number << std::endl;
Line 174:
In C++, the <code>std::map</code> class is [[Generic programming#Templates in C.2B.2B|templated]] which allows the [[data type]]s of keys and values to be different for different <code>map</code> instances. For a given instance of the <code>map</code> class the keys must be of the same base type. The same must be true for all of the values. Although <code>std::map</code> is typically implemented using a [[self-balancing binary search tree]], C++11 defines a second map called <code>[[std::unordered_map]]</code>, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the [[Standard Template Library]] (STL) as well, usually called <code>hash_map</code>, available from such implementations as SGI and STLPort.
 
===CFMLCobra===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
A structure in [[CFML]] is equivalent to an associative array:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
 
===ColdFusion Markup Language===
A structure in [[ColdFusion Markup Language]] (CFML) is equivalent to an associative array:
 
<syntaxhighlight lang=CFS>
Line 188 ⟶ 212:
writeDump(phoneBook); // entire struct
</syntaxhighlight>
 
===Cobra===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
 
===D===
[[D programming language|D]] offers direct support for associative arrays in the core language; such arrays are implemented as a chaining hash table with binary trees.<ref>{{Cite web|title=Associative Arrays - D Programming Language|url=httphttps://digitalmarsdlang.comorg/d/2.0spec/hash-map.html |titleaccess-date=Associative Arrays |accessdate=20112021-0205-01 07|datewebsite= dlang.org}}</ref> The equivalent example would be:
 
<syntaxhighlight lang=D"d">
int main() {
string[ string ] phone_book;
Line 230:
Looping through all properties and associated values, and printing them, can be coded as follows:
 
<syntaxhighlight lang=D"d">
foreach (key, value; phone_book) {
writeln("Number for " ~ key ~ ": " ~ value );
Line 238:
A property can be removed as follows:
 
<syntaxhighlight lang=D"d">
phone_book.remove("Sally Smart");
</syntaxhighlight>
 
===Delphi===
[[Borland Delphi (software)|Delphi]] supports several standard containers, including TDictionary<T>:
 
<syntaxhighlight lang=Delphi"delphi">
uses
SysUtils,
Line 265:
</syntaxhighlight>
 
Versions ofPre-2009 Delphi prior to 2009versions do not offer direct support for associative arrays directly. However, associativeSuch arrays can be simulated using the TStrings class:
 
<syntaxhighlight lang=Delphi"delphi">
procedure TForm1.Button1Click(Sender: TObject);
var
Line 293:
 
===Erlang===
[[Erlang (programming language)|Erlang]] offers many ways to represent mappings; twothree of the most common in the standard library are keylists, dictionaries, and dictionariesmaps.
 
====Keylists====
Keylists are lists of tuples, where the first element of each [[tuple]] is a key, and the second is a value. Functions for operating on keylists are provided in the <code>lists</code> module.
Keylists are lists of [[tuple]]s, where the first element of each tuple is a key, and the second is a value. Functions for operating on keylists are provided in the <code>lists</code> module.
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook = [{"Sally SmartSmith", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
Line 305 ⟶ 306:
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
{_, Phone} = lists:keyfind("Sally SmartSmith", 1, PhoneBook),
io:format("Phone number: ~s~n", [Phone]).
</syntaxhighlight>
 
====Dictionaries====
Dictionaries are implemented in the <code>dict</code> of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
Dictionaries are implemented in the <code>dict</code> module of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
Line 321 ⟶ 323:
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}]).
</syntaxhighlight>
 
The dictionary can be accessed using the <code>dict:find/2</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 334 ⟶ 337:
 
In both cases, any Erlang term can be used as the key. Variations include the <code>orddict</code> module, implementing ordered dictionaries, and <code>gb_trees</code>, implementing general balanced trees.
 
====Maps====
Maps were introduced in OTP 17.0,<ref>{{Cite web|title=Erlang -- maps|url=https://erlang.org/doc/man/maps.html|access-date=2021-03-07|website=erlang.org}}</ref> and combine the strengths of keylists and dictionaries. A map is defined using the syntax <code>#{ K1 => V1, ... Kn => Vn }</code>:
 
<syntaxhighlight lang="erlang">
PhoneBook = #{"Sally Smith" => "555-9999",
"John Doe" => "555-1212",
"J. Random Hacker" => "553-1337"}.
</syntaxhighlight>
 
Basic functions to interact with maps are available from the <code>maps</code> module. For example, the <code>maps:find/2</code> function returns the value associated with a key:
 
<syntaxhighlight lang="erlang">
{ok, Phone} = maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
 
Unlike dictionaries, maps can be pattern matched upon:
 
<syntaxhighlight lang="erlang">
#{"Sally Smith", Phone} = PhoneBook,
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
 
Erlang also provides syntax sugar for functional updates—creating a new map based on an existing one, but with modified values or additional keys:
 
<syntaxhighlight lang="erlang">
PhoneBook2 = PhoneBook#{
% the `:=` operator updates the value associated with an existing key
"J. Random Hacker" := "355-7331",
 
% the `=>` operator adds a new key-value pair, potentially replacing an existing one
"Alice Wonderland" => "555-1865"
}
</syntaxhighlight>
 
===F#===
 
===={{code|Map<'Key,'Value>}}====
At runtime, [[F Sharp (programming language)|F#]] provides the <code>Collections.Map<'Key,'Value></code> type, which is an immutable [[AVL tree]].
 
Line 343 ⟶ 381:
The following example calls the <code>Map</code> constructor, which operates on a list (a semicolon delimited sequence of elements enclosed in square brackets) of tuples (which in F# are comma-delimited sequences of elements).
 
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 353 ⟶ 391:
 
=====Access by key=====
Values can be looked up via one of the <code>Map</code> members, such as its indexer or <code>Item</code> property (which throw an [[Exception handling|exception]] if the key does not exist) or the <code>TryFind</code> function, which returns an [[option type]] with a value of <{{code>|Some <result></code>|f#}}, for a successful lookup, or <code>None</code>, for an unsuccessful one. [[Pattern matching]] can then be used to extract the raw value from the result, or a default value can be set.
 
<syntaxhighlight lang="fsharp">
let sallyNumber = numbers.["Sally Smart"]
// or
Line 369 ⟶ 407:
In both examples above, the <code>sallyNumber</code> value would contain the string <code>"555-9999"</code>.
 
===={{code|Dictionary<'TKey,'TValue>}}====
Because F# is a .NET language, it also has access to features of the [[.NET Framework]], including the <{{code>|System.Collections.Generic.Dictionary<'TKey,'TValue></code>|f#}} type (which is implemented as a [[hash table]]), which is the primary associative array type used in C# and Visual Basic. This type may be preferred when writing code that is intended to operate with other languages on the .NET Framework, or when the performance characteristics of a hash table are preferred over those of an AVL tree.
 
=====Creation=====
The <code>dict</code> function provides a means of conveniently creating a .NET dictionary that is not intended to be mutated; it accepts a sequence of tuples and returns an immutable object that implements <{{code>|IDictionary<'TKey,'TValue></code>|f#}}.
 
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 384 ⟶ 422:
</syntaxhighlight>
 
When a mutable dictionary is needed, the constructor of <{{code>|System.Collections.Generic.Dictionary<'TKey,'TValue></code>|f#}} can be called directly. See [[#C#|the C# example on this page]] for additional information.
 
<syntaxhighlight lang="fsharp">
let numbers = System.Collections.Generic.Dictionary<string, string>()
numbers.Add("Sally Smart", "555-9999")
Line 396 ⟶ 434:
<code>IDictionary</code> instances have an indexer that is used in the same way as <code>Map</code>, although the equivalent to <code>TryFind</code> is <code>TryGetValue</code>, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
 
<syntaxhighlight lang="fsharp">
let sallyNumber =
let mutable result = ""
Line 403 ⟶ 441:
 
F# also allows the function to be called as if it had no output parameter and instead returned a tuple containing its regular return value and the value assigned to the output parameter:
<syntaxhighlight lang="fsharp">
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
Line 421 ⟶ 459:
[[Visual FoxPro]] implements mapping with the Collection Class.
 
<syntaxhighlight lang="visualfoxprofoxpro">
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
Line 434 ⟶ 472:
[[Go (programming language)|Go]] has built-in, language-level support for associative arrays, called "maps". A map's key type may only be a boolean, numeric, string, array, struct, pointer, interface, or channel type.
 
A map type is written: <ttcode>map[keytype]valuetype</ttcode>
 
Adding elements one at a time:
 
<syntaxhighlight lang=Go"go">
phone_book := make(map[string] string) // make an empty map
phone_book["Sally Smart"] = "555-9999"
Line 447 ⟶ 485:
A map literal:
 
<syntaxhighlight lang=Go"go">
phone_book := map[string] string {
"Sally Smart": "555-9999",
Line 457 ⟶ 495:
Iterating through a map:
 
<syntaxhighlight lang=Go"go">
// over both keys and values
for key, value := range phone_book {
Line 470 ⟶ 508:
 
===Haskell===
The [[Haskell (programming language)|Haskell]] programming language provides only one kind of associative container – a list of pairs:
 
<syntaxhighlight lang="Haskellhaskell">
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
 
Line 482 ⟶ 520:
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just 'result{{' "}} when found.
 
The [[Glasgow Haskell Compiler|GHC]] (GHC), the most commonly used implementation of Haskell, provides two more types of associative containers. Other implementations mightmay also provide these.
 
One is polymorphic functional maps (represented as immutable balanced binary trees):
 
<syntaxhighlight lang="Haskellhaskell" highlight="1">
import qualified Data.Map as M
 
Line 515 ⟶ 553:
Just "555-1212"
 
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the [[Monad_Monad (functional_programmingfunctional programming)#IO_monadIO monad|IO monad]].
 
===Java===
In [[Java (programming language)|Java]] associative arrays are implemented as "maps", which are part of the [[Java collections framework]]. Since [[Java Platform, Standard Edition|J2SE]] 5.0 and the introduction of [[generic programming|generics]] into Java, collections can have a type specified; for example, an associative array that maps strings to strings might be specified as follows:
 
<syntaxhighlight lang=Java"java">
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
Line 529 ⟶ 567:
The {{Javadoc:SE|java/util|Map|get(java.lang.Object)|name=get}} method is used to access a key; for example, the value of the expression <code>phoneBook.get("Sally Smart")</code> is <code>"555-9999"</code>. This code uses a hash map to store the associative array, by calling the constructor of the {{Javadoc:SE|java/util|HashMap}} class. However, since the code only uses methods common to the interface {{Javadoc:SE|java/util|Map}}, a self-balancing binary tree could be used by calling the constructor of the {{Javadoc:SE|java/util|TreeMap}} class (which implements the subinterface {{Javadoc:SE|java/util|SortedMap}}), without changing the definition of the <code>phoneBook</code> variable, or the rest of the code, or using other underlying data structures that implement the <code>Map</code> interface.
 
The hash function in Java, used by HashMap and HashSet, is provided by the {{Javadoc:SE|java/lang|Object|hashCode()}} method. Since every class in Java [[Inheritance (computerobject-oriented scienceprogramming)|inherits]] from {{Javadoc:SE|java/lang|Object}}, every object has a hash function. A class can [[Method overriding (programming)|override]] the default implementation of <code>hashCode()</code> to provide a custom hash function more in accordance with the properties of the object.
 
The <code>Object</code> class also contains the {{Javadoc:SE|name=equals(Object)|java/lang|Object|equals(java.lang.Object)}} method, which tests an object for equality with another object. Hashed data structures in Java rely on objects maintaining the following contract between their <code>hashCode()</code> and <code>equals()</code> methods:
Line 535 ⟶ 573:
For two objects ''a'' and ''b'',
 
<syntaxhighlight lang=Java"java">
a.equals(b) == b.equals(a)
if a.equals(b), then a.hashCode() == b.hashCode()
Line 551 ⟶ 589:
 
====Map and WeakMap====
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default.; Itit only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
 
=====Creation=====
A map can be initialized with all items during construction:
 
<syntaxhighlight lang=JavaScript"javascript">
varconst phoneBook = new Map([
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
Line 566 ⟶ 604:
Alternatively, you can initialize an empty map and then add items:
 
<syntaxhighlight lang=JavaScript"javascript">
varconst phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
Line 574 ⟶ 612:
 
=====Access by key=====
Accessing an element of the map can be done with the "<code>get"</code> method:
 
<syntaxhighlight lang=JavaScript"javascript">
varconst sallyNumber = phoneBook.get("Sally Smart");
</syntaxhighlight>
 
In this example, the sallyNumber value <code>sallyNumber</code> will now contain the string "555-9999".
 
=====Enumeration=====
The keys in a map are ordered. Thus, when iterating through it, a map object returns keys in order of insertion. The following demonstrates enumeration using a for-loop:
 
<syntaxhighlight lang=JavaScript"javascript">
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
console.log('`Phone number for ${name} is ${number}'`);
}
</syntaxhighlight>
Line 594 ⟶ 632:
A key can be removed as follows:
 
<syntaxhighlight lang=JavaScript"javascript">
phoneBook.delete("Sally Smart");
</syntaxhighlight>
Line 603 ⟶ 641:
However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could conflict with user-defined keys. So, doing a lookup for a property will point the lookup to the prototype's definition if the object does not define the property.
 
An object literal is written as <code>{ property1 : value1, property2 : value2, ... }</code>. For example:
 
<syntaxhighlight lang=JavaScript"javascript">
varconst myObject = {
"Sally Smart" : "555-9999",
"John Doe" : "555-1212",
"J. Random Hacker" : "553-1337",
};
</syntaxhighlight>
 
To prevent the lookup from using the prototype's properties, you can use the <code>Object.setPrototypeOf</code> function:
 
<syntaxhighlight lang=JavaScript>
Line 619 ⟶ 657:
</syntaxhighlight>
 
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using <code>Object.create(null)</code>:
 
<syntaxhighlight lang=JavaScript>
varconst myObject = Object.create(null);
 
Object.assign(myObject, {
"Sally Smart" : "555-9999",
"John Doe" : "555-1212",
"J. Random Hacker" : "553-1337",
});
</syntaxhighlight>
Line 634 ⟶ 672:
 
<syntaxhighlight lang=JavaScript>
varconst myOtherObject = { foo : 42, bar : false };
</syntaxhighlight>
 
Line 647 ⟶ 685:
 
<syntaxhighlight lang=JavaScript>
for (varconst property in myObject) {
var const value = myObject[property];
console.log("`myObject[" + ${property + "}] = " + ${value}`);
}
</syntaxhighlight>
Line 656 ⟶ 694:
 
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
console.log(`${property} = ${value}`);
}
</syntaxhighlight>
Line 670 ⟶ 708:
 
<syntaxhighlight lang=JavaScript>
myObject[1] // key is "1"; note that myObject[1] == myObject['"1'"]
myObject[['"a'",' "b'"]] // key is "a,b"
myObject[{ toString:function() { return '"hello world'"; } }] // key is "hello world"
</syntaxhighlight>
 
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and <code>Map</code>/<code>WeakMap</code> classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, 'for( and for-in)' loops will work as expected on associative 'arrays'. This issue has been brought to the fore by the popularity of JavaScript frameworks that make heavy and sometimes indiscriminate use of prototypes to extend JavaScript's inbuilt types.
 
See [http://blog.metawrap.com/2006/05/30/june-6th-is-javascript-array-and-object-prototype-awareness-day/ JavaScript Array And Object Prototype Awareness Day] for more information on the issue.
Line 685 ⟶ 723:
Declare dictionary:
<syntaxhighlight lang="julia">
phonebook = Dict( "Sally Smart" => "555-9999", "John Doe" => "555-1212", "J. Random Hacker" => "555-1337" )
</syntaxhighlight>
 
Access element:
 
<syntaxhighlight lang="julia">
phonebook["Sally Smart"]
phonebook["Sally Smart"]
</syntaxhighlight>
 
Add element:
<syntaxhighlight lang="julia">
 
phonebook["New Contact"] = "555-2222"
</syntaxhighlight>
 
Delete element:
<syntaxhighlight lang="julia">
delete!(phonebook, "Sally Smart")
</syntaxhighlight>
 
Get keys and values as [[Iterator#Implicit iterators|iterables]]:
delete!(phonebook, "Sally Smart")
<syntaxhighlight lang="julia">
 
keys(phonebook)
Get keys and values as [[Iterator#Implicit_iterators|iterables]]:
values(phonebook)
 
</syntaxhighlight>
keys(phonebook)
values(phonebook)
 
===KornShell 93, and compliant shells===
Line 711 ⟶ 754:
Definition:
<syntaxhighlight lang="ksh">
typeset -A phonebook; # ksh93; in bash4+, "typeset" is a synonym of the more preferred "declare", which works identically in this case
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
declare -A phonebook; # bash4
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
</syntaxhighlight>
 
Dereference:
<syntaxhighlight lang="ksh">
${phonebook["John Doe"]};
</syntaxhighlight>
 
Line 743 ⟶ 785:
</syntaxhighlight>
 
This function can be construed as aan accommodation for <code>cons</code> operations.<ref>{{cite web |title=Common Lisp the Language, 2nd Edition: 15.6. Association Lists |url=https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node153.html |website=Carnegie Mellon University |access-date=3 August 2020}}</ref>
 
<syntaxhighlight lang=Lisp>
Line 760 ⟶ 802:
</syntaxhighlight>
 
Searching for an entry by its key is performed via <code>assoc</code>, which might be configured for the test predicate and direction, especially searching the association list from its end to its front. The result, if positive, returns the entire entry cons, not only its value. Failure to obtain a matching key ledsleads to a return of the <code>NIL</code> value.
 
<syntaxhighlight lang=Lisp>
Line 1,032 ⟶ 1,074:
 
<syntaxhighlight lang="mathematica">
phonebook = <| "Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337" |>;
</syntaxhighlight>
 
Line 1,040 ⟶ 1,082:
 
<syntaxhighlight lang="mathematica">
phonebook[[Key["Sally Smart"]]]
</syntaxhighlight>
 
Line 1,046 ⟶ 1,088:
 
<syntaxhighlight lang="mathematica">
phonebook[["Sally Smart"]]
</syntaxhighlight>
 
Line 1,099 ⟶ 1,141:
</syntaxhighlight>
 
In Mac OS X 10.5+ and iPhone OS, dictionary keys can be enumerated more concisely using the <code>NSFastEnumeration</code> construct:<ref>{{cite web |title=NSFastEnumeration Protocol Reference |url=https://developer.apple.com/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |date=2011 |archive-url=https://web.archive.org/web/20160313082808/https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |archive-date=13 March 2016 |website=Mac Developer Library |access-date=3 August 2020}}</ref>
 
<syntaxhighlight lang=ObjC>
Line 1,183 ⟶ 1,225:
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
 
Line 1,192 ⟶ 1,234:
 
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
 
Line 1,199 ⟶ 1,241:
 
// iterate over the keys
for (String name : phoneBook.keys) {
System.out.println(name + " -> " + phoneBook[name]);
}
// phoneBook[name] access a value by a key (it looks like java array access)
Line 1,210 ⟶ 1,252:
 
<syntaxhighlight lang=Java>
int[String][][double] a;
java.util.Map<String[Object], Integer> b;
</syntaxhighlight>
 
Line 1,227 ⟶ 1,269:
</syntaxhighlight>
 
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> – the key is surrounded by [[Bracket#Curly_bracketCurly bracket|curly braces]] and the hash name is prefixed by a <code>$</code>, indicating that the hash element itself is a scalar value, even though it is part of a hash. The value of <code>$phone_book{'John Doe'}</code> is <code>'555-1212'</code>. The <code>%</code> sigil is only used when referring to the hash as a whole, such as when asking for <code>keys %phone_book</code>.
 
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash:
Line 1,333 ⟶ 1,375:
 
===PHP===
[[PHP]]'s built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores arrays as associative arrays.<ref>About the implementation of [http://se.php.net/manual/en/language.types.array.php Arrays] in PHP</ref> So, PHP can have non-consecutively numerically- indexed arrays. The keys have to be of integer (floating point numbers are truncated to integer) or string type, while values can be of arbitrary types, including other arrays and objects. The arrays are heterogeneous: a single array can have keys of different types. PHP's associative arrays can be used to represent trees, lists, stacks, queues, and other common data structures not built into PHP.
 
An associative array can be declared using the following syntax:
Line 1,504 ⟶ 1,546:
</syntaxhighlight>
 
ToDictionary accessitems ancan entrybe inaccessed Python simply useusing the array indexing operator:
<syntaxhighlight lang="python">
>>> phonebook["Sally Smart"]
Line 1,539 ⟶ 1,581:
</syntaxhighlight>
 
Python 2.7 and 3.x also support dictionary[https://peps.python.org/pep-0274/ dict comprehensions] (similar to [[list comprehension]]s), a compact syntax for generating a dictionary from any iterator:
 
<syntaxhighlight lang="python">
Line 1,635 ⟶ 1,677:
In [[Ruby programming language|Ruby]] a hash table is used as follows:
 
<syntaxhighlight lang="irbrb">
irb(main):001:0> phonebook = {
irb(main):002:1* 'Sally Smart' => '555-9999',
irb(main):003:1* 'John Doe' => '555-1212',
irb(main):004:1* 'J. Random Hacker' => '553-1337'
}
irb(main):005:1> }
phonebook['John Doe']
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):006:0> phonebook['John Doe']
=> "555-1212"
</syntaxhighlight>
 
Line 1,672 ⟶ 1,712:
 
===Rust===
The [[Rust (programming language)|Rust]] standard library provides a hash map (<code>std::collections::HashMap</code>) and a [[B-tree]] map (<code>std::collections::BTreeMap</code>). They share several methods with the same names, but have different requirements for the types of keys that can be inserted. The <code>HashMap</code> requires keys to implement the <code>Eq</code> ([[equivalence relation]]) and <code>Hash</code> (hashability) traits and it stores entries in an unspecified order, and the <code>BTreeMap</code> requires the <code>Ord</code> ([[total order]]) trait for its keys and it stores entries in an order defined by the key type. The order is reflected by the default iterators.
 
<syntaxhighlight lang="rust">
Line 1,697 ⟶ 1,737:
 
===S-Lang===
[[S-Lang (programming language)|S-Lang]] has an associative array type:
 
<syntaxhighlight lang="text">
Line 1,780 ⟶ 1,820:
The SML'97 standard of the [[Standard ML]] programming language does not provide any associative containers. However, various implementations of Standard ML do provide associative containers.
 
The library of the popular [[Standard ML of New Jersey]] (SML/NJ) implementation provides a signature (somewhat like an "interface"), <code>ORD_MAP</code>, which defines a common interface for ordered functional (immutable) associative arrays. There are several general functors—<code>BinaryMapFn</code>, <code>ListMapFn</code>, <code>RedBlackMapFn</code>, and <code>SplayMapFn</code>—that allow you to create the corresponding type of ordered map (the types are a [[self-balancing binary search tree]], sorted [[association list]], [[red-blackred–black tree]], and [[splay tree]], respectively) using a user-provided structure to describe the key type and comparator. The functor returns a structure in accordance with the <code>ORD_MAP</code> interface. In addition, there are two pre-defined modules for associative arrays that employ integer keys: <code>IntBinaryMap</code> and <code>IntListMap</code>.
 
<syntaxhighlight lang="sml">
Line 1,894 ⟶ 1,934:
[[Visual Basic]] can use the Dictionary class from the [[Windows Scripting Host|Microsoft Scripting Runtime]] (which is shipped with Visual Basic 6). There is no standard implementation common to all versions:
 
<syntaxhighlight lang=VB"vbnet">
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
Line 1,929 ⟶ 1,969:
 
====Access by key====
Example demonstrating access (see [[#C# access|C# access]]):
 
<syntaxhighlight lang=VBNet>
Line 2,047 ⟶ 2,087:
"J. Random Hacker": "555-1337"
}
</syntaxhighlight>
 
=== TOML ===
[[TOML]] is designed to map directly to a hash map. TOML refers to associative arrays as tables. Tables within TOML can be expressed in either an "unfolded" or an inline approach. Keys can only be strings.<syntaxhighlight lang="toml">[phonebook]
"Sally Smart" = "555-9999"
"John Doe" = "555-1212"
"J. Random Hacker" = "555-1337"</syntaxhighlight><syntaxhighlight lang="toml">
phonebook = { "Sally Smart" = "555-9999", "John Doe" = "555-1212", "J. Random Hacker" = "555-1337" }
 
</syntaxhighlight>