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

Content deleted Content added
m F#: {{code}}
 
(360 intermediate revisions by more than 100 users not shown)
Line 1:
{{ProgLangCompare}}
{{TOC limit|3}}
== Language support ==
{{Expand|date=January 2007}}
 
The following is aThis '''comparison of programming languages (associative arrays)''' (alsocompares "mapping",the "hash",features andof "dictionary")[[associative inarray]] various[[data programmingstructure]]s languages.or Forarray-lookup moreprocessing details,for seeover 40 computer [[Associativeprogramming arraylanguage]]s.
 
===Language Awk =support==
{{Dynamic list}}
[[Awk]] has built-in, language-level support for associative arrays.
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
 
===AWK===
[[AWK]] has built-in, language-level support for associative arrays.
 
For example:
 
<sourcesyntaxhighlight lang="textawk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
phonebook["J. Random Hacker"] = "555-1337"
</syntaxhighlight>
</source>
 
YouThe canfollowing alsocode looploops through an associated array asand followsprints its contents:
 
<sourcesyntaxhighlight lang="text"awk>
for (name in phonebook) {
print name, " ", phonebook[name]
}
</syntaxhighlight>
</source>
 
YouThe user can alsosearch checkfor if an element iselements in thean associative array, and delete elements from an associativethe array.
 
MultiThe following shows how multi-dimensional associative arrays can be implementedsimulated in standard AwkAWK using concatenation and e.g.the built-in string-separator variable SUBSEP:
 
<sourcesyntaxhighlight lang="text"awk>
{ # for every input line
multi[$1 SUBSEP $2]++;
Line 39 ⟶ 42:
}
}
</syntaxhighlight>
</source>
 
===C===
Thompson AWK [http://www.tasoft.com/tawk.html] provides built-in multi-dimensional associative arrays:
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=https://uthash.sourceforge.net/ |website=Github |access-date=3 August 2020}}</ref>
<source lang="text">
{ # for every input line
multi[$1][$2]++;
}
#
END {
for (x in multi)
for (y in multi[x])
print x, y, multi[x][y];
}
</source>
 
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>
=== C ===
There is no standard implementation of an associative array in C, but a 3rd party library with BSD license is available [http://www.cl.cam.ac.uk/~cwc22/hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code>.
 
Similar to [[GLib]], [[Apple Inc.|Apple]]'s cross-platform [[Core Foundation]] framework provides several basic data types. In particular, there are reference-counted CFDictionary and CFMutableDictionary.
Another 3rd party library, [http://uthash.sourceforge.net/ uthash], also creates associative arrays from C structures. A structure represents a value, and one of the structure fields acts as the key.
 
===C#===
Finally, the [[Glib]] library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.
<!-- Note: Be aware when editing that this section and its subsections are linked to by the F# and Visual Basic .NET sections -->
[[C Sharp (programming language)|C#]] uses the collection classes provided by the [[.NET Framework]]. The most commonly used associative array type is <code>System.Collections.Generic.Dictionary<TKey, TValue></code>, which is implemented as a mutable hash table. The relatively new <code>System.Collections.Immutable</code> package, available in .NET Framework versions 4.5 and above, and in all versions of [[.NET Core]], also includes the <code>System.Collections.Immutable.Dictionary<TKey, TValue></code> type, which is implemented using an [[AVL tree]]. The methods that would normally mutate the object in-place instead return a new object that represents the state of the original object after mutation.
 
=== ColdFusion =Creation====
The following demonstrates three means of populating a mutable dictionary:
You can use a ColdFusion structure to perform as an associative array. Here is a sample in [[ColdFusion]]:
* the <code>Add</code> method, which adds a key and value and throws an [[exception handling|exception]] if the key already exists in the dictionary;
* assigning to the indexer, which overwrites any existing value, if present; and
* 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).
 
<sourcesyntaxhighlight lang="cfmcsharp">
var dictionary = new Dictionary<string, string>();
<cfscript>
dictionary.Add("Sally Smart", "555-9999");
phoneBook = StructNew();
phoneBookdictionary["SallyJohn SmartDoe"] = "555-99991212";
// Not allowed in C#.
phoneBook["John Doe"] = "555-1212";
phoneBook[// dictionary.Item("J. Random Hacker"]) = "555553-1337";
dictionary["J. Random Hacker"] = "553-1337";
sName = "A Person";
</syntaxhighlight>
phoneBook[sName] = "555-4321";
phoneBook.UnknownComic = "???";
</cfscript>
 
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to <code>Add</code>.
<!-- will output 3 question marks below: -->
<cfoutput>
#phoneBook["UnknownComic"]#
</cfoutput>
</source>
 
<syntaxhighlight lang="csharp">
=== C# ===
var dictionary = new Dictionary<string, string> {
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
{ "J. Random Hacker", "553-1337" }
};
</syntaxhighlight>
 
===={{anchor|C# access}}Access by key====
<source lang="csharp">
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.
Hashtable ht = new Hashtable();
ht.Add("testKey", "AssociatedData");
MessageBox.Show((string) ht["testKey"]);
</source>
 
<sourcesyntaxhighlight lang="csharp">
var sallyNumber = dictionary["Sally Smart"];
Dictionary<int, string> dic = new Dictionary<int, string>();
</syntaxhighlight>
dic.Add(7, "Bond");
<syntaxhighlight lang="csharp">
MessageBox.Show(dic[7]);
var sallyNumber = (dictionary.TryGetValue("Sally Smart", out var result) ? result : "n/a";
</source>
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
 
===={{anchor|C# enumeration}}Enumeration====
In the above sample the Hashtable class is only capable of associating a String key with a value of Object type. Because in .NET all types (save pointers) ultimately derive from Object anything can be put into a Hashtable, even data of different types. This could lead to errors if consuming code expects data to be of a singular type. In the above code casting is required to convert the Object variables back to their original type. Additionally, casting value-types (structures such as integers) to Object to put into the Hashtable and casting them back requires boxing/unboxing which incurs both a slight performance penalty and pollutes the heap with garbage. This changes in C# 2.0 with generic hashtables called dictionaries. There are significant performance and reliability gains to these strongly typed collections because they do not require boxing/unboxing or explicit type casts and introduce compile-time type checks.
A dictionary can be viewed as a sequence of keys, sequence of values, or sequence of pairs of keys and values represented by instances of the <code>KeyValuePair<TKey, TValue></code> type, although there is no guarantee of order. For a sorted dictionary, the programmer could choose to use a <code>SortedDictionary<TKey, TValue></code> or use the <code>.Sort</code> [[Language Integrated Query|LINQ]] extension method when enumerating.
 
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang="csharp">
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in dictionary)
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
}
</syntaxhighlight>
 
=== C++ ===
[[C++]] also 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 samefollowing information as abovecode usingin C++ with the following code:
 
<sourcesyntaxhighlight lang="cpp">
#include <map>
#include <string>
#include <utility>
int main() {
std::map<std::string, std::string> phone_book;
phone_book.insert(std::make_pair("Sally Smart", "555-9999"));
phone_book.insert(std::make_pair("John Doe", "555-1212"));
phone_book.insert(std::make_pair("J. Random Hacker", "553-1337"));
}
</syntaxhighlight>
 
Or less efficiently, as this creates temporary <code>std::string</code> values:
<syntaxhighlight lang="cpp">
#include <map>
#include <string>
Line 110 ⟶ 131:
phone_book["John Doe"] = "555-1212";
phone_book["J. Random Hacker"] = "553-1337";
return 0;
}
</syntaxhighlight>
</source>
 
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:
You can iterate through the list with the following code:
 
<sourcesyntaxhighlight lang="cpp">
#include <map>
std::map<std::string, std::string>::iterator curr,end;
#include <string>
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; curr++)
 
int main() {
std::map<std::string, std::string> phone_book {
{"Sally Smart", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}
};
}
</syntaxhighlight>
 
You can iterate through the list with the following code (C++03):
 
<syntaxhighlight lang="cpp">
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
std::cout << curr->first << " = " << curr->second << std::endl;
</syntaxhighlight>
</source>
 
The same task in C++11:
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++'s [[Technical Report 1]] (TR1) defines a second map called <code>std::tr1::unordered_map</code> with the algorithmic characteristics of a hash table. This is a common vendor extension to the STL as well, usually called <code>hash_map</code>, being available from such implementations as SGI and STLPort.
 
<syntaxhighlight lang="cpp">
=== Cocoa/GNUstep (Objective-C) ===
for(const auto& curr : phone_book)
[[Cocoa (API)]] and [[GNUstep]] handle associative arrays using <code>NSMutableDictionary</code> (a mutable version of <code>NSDictionary</code>) class cluster. This class allows assignments between any two objects to be made. A copy of the key object is made before it is inserted into <code>NSMutableDictionary</code>, therefore the keys must conform to the <code>NSCopying</code> protocol. When being inserted to a dictionary, the value object receives a retain message to increase its reference count. The value object will receive the release message when it will be deleted from the dictionary (both explicitly or by adding to the dictionary a different object with the same key).
std::cout << curr.first << " = " << curr.second << std::endl;
<source lang="objc">
</syntaxhighlight>
NSMutableDictionary *aDictionary = <nowiki>[[</nowiki>NSMutableDictionary alloc] init];
 
[aDictionary setObject:@"555-9999" forKey:@"Sally Smart"];
Using the structured binding available in [[C++17]]:
[aDictionary setObject:@"555-1212" forKey:@"John Doe"];
 
[aDictionary setObject:@"553-1337" forKey:@"Random Hacker"];
<syntaxhighlight lang="cpp">
</source>
for (const auto& [name, number] : phone_book) {
To access assigned objects this command may be used:
std::cout << name << " = " << number << std::endl;
<source lang="objc">
id anObject = [aDictionary objectForKey:@"Sally Smart"];
</source>
All keys or values can be simply enumerated using <code>NSEnumerator</code>
<source lang="objc">
NSEnumerator *keyEnumerator = <nowiki>[[</nowiki>aDictionary allKeys] objectEnumerator];
id key;
while (( key = [keyEnumerator nextObject] ))
{
// ... process it here ...
}
</syntaxhighlight>
</source>
 
What is even more practical, structured data graphs may be easily created using [[Cocoa (API)|Cocoa]], especially <code>NSDictionary</code> (<code>NSMutableDictionary</code>). This can be illustrated with this compact example:
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.
<source lang="objc">
 
NSDictionary *aDictionary =
===Cobra===
[NSDictionary dictionaryWithObjectsAndKeys:
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
[NSDictionary dictionaryWithObjectsAndKeys:
{{sxhl|2=python|1=<nowiki/>
@"555-9999", @"Sally Smart",
dic as Dictionary<of String, String> = Dictionary<of String, String>()
@"555-1212", @"John Doe",
dic.add('Sally Smart', '555-9999')
nil], @"students",
dic.add('John Doe', '555-1212')
[NSDictionary dictionaryWithObjectsAndKeys:
dic.add('J. Random Hacker', '553-1337')
@"553-1337", @"Random Hacker",
nil], @"hackers",
assert dic['Sally Smart'] == '555-9999'
nil];
}}
</source>
Alternatively, a dictionary can be initialized with all items during construction:
And relevant fields can be quickly accessed using key paths:
{{sxhl|2=python|1=<nowiki/>
<source lang="objc">
dic = {
id anObject = [aDictionary valueForKeyPath:@"students.Sally Smart"];
'Sally Smart':'555-9999',
</source>
'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>
dynamicKeyName = "John Doe";
phoneBook = {
"Sally Smart" = "555-9999",
"#dynamicKeyName#" = "555-4321",
"J. Random Hacker" = "555-1337",
UnknownComic = "???"
};
writeOutput(phoneBook.UnknownComic); // ???
writeDump(phoneBook); // entire struct
</syntaxhighlight>
 
=== 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=https://dlang.org/spec/hash-map.html|access-date=2021-05-07|website=dlang.org}}</ref> The equivalent example would be:
in the core language - they are implemented as trees {{Fact|date=March 2007}}. The equivalent example would be:
 
<sourcesyntaxhighlight lang="d">
int main() {
charstring[][char[] string ] phone_book;
phone_book["Sally Smart"] = "555-9999";
phone_book["John Doe"] = "555-1212";
Line 175 ⟶ 224:
return 0;
}
</syntaxhighlight>
</source>
 
Keys and values can be any types, but all the keys in an associative array must be of the same type, and the same goes for dependent values.
must be of the same type, and the same for values.
 
You can also loopLooping through all properties and associated values, i.e.and printing them, can be coded as follows:
 
<sourcesyntaxhighlight lang="d">
foreach (key, value; phone_book) {
writefln writeln("Number for $name" ~ key ~ ": $number\n", key,~ value );
}
</syntaxhighlight>
</source>
 
A property can be removed as follows:
 
<sourcesyntaxhighlight lang="d">
phone_book.remove("Sally Smart");
</syntaxhighlight>
</source>
 
=== Delphi ===
[[Delphi (software)|Delphi]] supports several standard containers, including TDictionary<T>:
[[Borland Delphi|Delphi]] does not offer direct support for associative arrays. However, you can simulate associative arrays using TStrings object. Here's an example:
 
<sourcesyntaxhighlight lang="delphi">
uses
SysUtils,
Generics.Collections;
 
var
PhoneBook: TDictionary<string, string>;
Entry: TPair<string, string>;
 
begin
PhoneBook := TDictionary<string, string>.Create;
PhoneBook.Add('Sally Smart', '555-9999');
PhoneBook.Add('John Doe', '555-1212');
PhoneBook.Add('J. Random Hacker', '553-1337');
 
for Entry in PhoneBook do
Writeln(Format('Number for %s: %s',[Entry.Key, Entry.Value]));
end.
</syntaxhighlight>
 
Pre-2009 Delphi versions do not support associative arrays directly. Such arrays can be simulated using the TStrings class:
 
<syntaxhighlight lang="delphi">
procedure TForm1.Button1Click(Sender: TObject);
var
Line 220 ⟶ 290:
DataField.Free;
end;
</syntaxhighlight>
</source>
 
=== Java Erlang===
[[Erlang (programming language)|Erlang]] offers many ways to represent mappings; three of the most common in the standard library are keylists, dictionaries, and maps.
In [[Java (programming language)|Java]] associative arrays are implemented as "maps"; they are part of the [[Java collections framework]]. Since [[J2SE]] 5.0 and the introduction of [[generic programming|generics]] into Java, collections can have a type specified; for example, an associative array mapping strings to strings might be specified as follows:
 
====Keylists====
<source lang="java">
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">
PhoneBook = [{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
</syntaxhighlight>
 
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
 
<syntaxhighlight lang="erlang">
{_, Phone} = lists:keyfind("Sally Smith", 1, PhoneBook),
io:format("Phone number: ~s~n", [Phone]).
</syntaxhighlight>
 
====Dictionaries====
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">
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
PhoneBook3 = dict:store("John Doe", "555-1212", Dict2),
PhoneBook = dict:store("J. Random Hacker", "553-1337", Dict3).
</syntaxhighlight>
 
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
 
<syntaxhighlight lang="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">
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
</syntaxhighlight>
 
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]].
 
=====Creation=====
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 =
[
"Sally Smart", "555-9999";
"John Doe", "555-1212";
"J. Random Hacker", "555-1337"
] |> Map
</syntaxhighlight>
 
=====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>|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
let sallyNumber = numbers.Item("Sally Smart")
</syntaxhighlight>
<syntaxhighlight lang=fsharp>
let sallyNumber =
match numbers.TryFind("Sally Smart") with
| Some(number) -> number
| None -> "n/a"
</syntaxhighlight>
 
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>|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>|f#}}.
 
<syntaxhighlight lang="fsharp">
let numbers =
[
"Sally Smart", "555-9999";
"John Doe", "555-1212";
"J. Random Hacker", "555-1337"
] |> dict
</syntaxhighlight>
 
When a mutable dictionary is needed, the constructor of {{code|System.Collections.Generic.Dictionary<'TKey,'TValue>|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")
numbers.["John Doe"] <- "555-1212"
numbers.Item("J. Random Hacker") <- "555-1337"
</syntaxhighlight>
 
=====Access by key=====
<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 = ""
if numbers.TryGetValue("Sally Smart", &result) then result else "n/a"
</syntaxhighlight>
 
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
| true, number -> number
| _ -> "n/a"
</syntaxhighlight>
 
====Enumeration====
A dictionary or map can be enumerated using <code>Seq.map</code>.
 
<syntaxhighlight lang=fsharp>
// loop through the collection and display each entry.
numbers |> Seq.map (fun kvp -> printfn "Phone number for %O is %O" kvp.Key kvp.Value)
</syntaxhighlight>
 
===FoxPro===
[[Visual FoxPro]] implements mapping with the Collection Class.
 
<syntaxhighlight lang="foxpro">
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
index = mapping.GetKey("flower2") && returns the index value 1
object = mapping("flower2") && returns "Daffodils" (retrieve by key)
object = mapping(1) && returns "Daffodils" (retrieve by index)
</syntaxhighlight>
 
GetKey returns 0 if the key is not found.
 
===Go===
[[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: <code>map[keytype]valuetype</code>
 
Adding elements one at a time:
 
<syntaxhighlight lang="go">
phone_book := make(map[string] string) // make an empty map
phone_book["Sally Smart"] = "555-9999"
phone_book["John Doe"] = "555-1212"
phone_book["J. Random Hacker"] = "553-1337"
</syntaxhighlight>
 
A map literal:
 
<syntaxhighlight lang="go">
phone_book := map[string] string {
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"J. Random Hacker": "553-1337",
}
</syntaxhighlight>
 
Iterating through a map:
 
<syntaxhighlight lang="go">
// over both keys and values
for key, value := range phone_book {
fmt.Printf("Number for %s: %s\n", key, value)
}
 
// over just keys
for key := range phone_book {
fmt.Printf("Name: %s\n", key)
}
</syntaxhighlight>
 
===Haskell===
The [[Haskell]] programming language provides only one kind of associative container – a list of pairs:
 
<syntaxhighlight lang="haskell">
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
 
main = print (lookup "John Doe" m)
</syntaxhighlight>
output:
Just "555-1212"
 
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), the most commonly used implementation of Haskell, provides two more types of associative containers. Other implementations may also provide these.
 
One is polymorphic functional maps (represented as immutable balanced binary trees):
 
<syntaxhighlight lang="haskell" highlight="1">
import qualified Data.Map as M
 
m = M.insert "Sally Smart" "555-9999" M.empty
m' = M.insert "John Doe" "555-1212" m
m'' = M.insert "J. Random Hacker" "553-1337" m'
 
main = print (M.lookup "John Doe" m'' :: Maybe String)
</syntaxhighlight>
output:
Just "555-1212"
 
A specialized version for integer keys also exists as Data.IntMap.
 
Finally, a polymorphic hash table:
 
<syntaxhighlight lang="haskell">
import qualified Data.HashTable as H
 
main = do m <- H.new (==) H.hashString
H.insert m "Sally Smart" "555-9999"
H.insert m "John Doe" "555-1212"
H.insert m "J. Random Hacker" "553-1337"
foo <- H.lookup m "John Doe"
print foo
</syntaxhighlight>
output:
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 (functional programming)#IO 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">
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
phoneBook.put("John Doe", "555-1212");
phoneBook.put("J. Random Hacker", "555-1337");
</syntaxhighlight>
</source>
 
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 <code>get</code> 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>.
 
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 (object-oriented programming)|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.
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}}, one could also use a self-balancing binary tree 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 use a number of other underlying data structures that implement the <code>Map</code> interface.
 
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:
The hash function in Java is provided by the method {{Javadoc:SE|java/lang|Object|hashCode()}}. Since every class in Java [[Inheritance (computer science)|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 based on the properties of the object.
 
The <code>Object</code> class also contains the method {{Javadoc:SE|name=equals(Object)|java/lang|Object|equals(java.lang.Object)}} that tests the object for equality with another object. Maps in Java rely on objects maintaining the following contract between their <code>hashCode()</code> and <code>equals()</code> methods:
 
For two objects ''a'' and ''b'',
 
* <source lang="java">a.equals(b) == b.equals(a)</source>
<syntaxhighlight lang="java">
* <source lang="java">if a.equals(b), then a.hashCode() == b.hashCode()</source>
a.equals(b) == b.equals(a)
if a.equals(b), then a.hashCode() == b.hashCode()
</syntaxhighlight>
 
In order to maintain this contract, a class that overrides <code>equals()</code> must also override <code>hashCode()</code>, and vice versa, so that <code>hashCode()</code> is based on the same properties (or a subset of the properties) as <code>equals()</code>.
 
A further contract that thea maphashed data structure has with the object is that the results of the <code>hashCode()</code> and <code>equals()</code> methods will not change once the object has been inserted into the map. For this reason, it is generally a good practice to base the hash function on [[Immutable object|immutable]] properties of the object.
 
Analogously, TreeMap, and other sorted data structures, require that an ordering be defined on the data type. Either the data type must already have defined its own ordering, by implementing the {{Javadoc:SE|java/lang|Comparable}} interface; or a custom {{Javadoc:SE|java/util|Comparator}} must be provided at the time the map is constructed. As with HashMap above, the relative ordering of keys in a TreeMap should not change once they have been inserted into the map.
=== JavaScript ===
JavaScript (and its standardized version: [[ECMAScript]]) is a [[Prototype-based programming|prototype-based]] [[Object-oriented programming|object-oriented]] language. In JavaScript an object is a mapping from property names to values -- that is, an associative array with one caveat: since property names are strings, only string keys are allowed. Other than that difference, objects also include one feature unrelated to associative arrays: a prototype link to the object they inherit from. Doing a lookup for a property will forward the lookup to the prototype if the object does not define the property itself.
 
===JavaScript===
An object literal is written as <code>{ property1 : value1, property2 : value2, ... }</code>. For example:
 
[[JavaScript]] (and its standardized version, [[ECMAScript]]) is a [[Prototype-based programming|prototype-based]] [[Object-oriented programming|object-oriented]] language.
<source lang="javascript">
 
var myObject = {
====Map and WeakMap====
"Sally Smart" : "555-9999",
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default; it only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
"John Doe" : "555-1212",
 
"J. Random Hacker" : "553-1337"
=====Creation=====
A map can be initialized with all items during construction:
 
<syntaxhighlight lang="javascript">
const phoneBook = new Map([
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
 
Alternatively, you can initialize an empty map and then add items:
 
<syntaxhighlight lang="javascript">
const phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
phoneBook.set("J. Random Hacker", "553-1337");
</syntaxhighlight>
 
=====Access by key=====
Accessing an element of the map can be done with the <code>get</code> method:
 
<syntaxhighlight lang="javascript">
const sallyNumber = phoneBook.get("Sally Smart");
</syntaxhighlight>
 
In this example, the 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">
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
console.log(`Phone number for ${name} is ${number}`);
}
</syntaxhighlight>
 
A key can be removed as follows:
 
<syntaxhighlight lang="javascript">
phoneBook.delete("Sally Smart");
</syntaxhighlight>
 
====Object====
An object is similar to a map—both let you set keys to values, retrieve those values, delete keys, and detect whether a value is stored at a key. For this reason (and because there were no built-in alternatives), objects historically have been used as maps.
 
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">
const myObject = {
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"J. Random Hacker": "553-1337",
};
</syntaxhighlight>
</source>
 
To prevent the lookup from using the prototype's properties, you can use the <code>Object.setPrototypeOf</code> function:
 
<syntaxhighlight lang=JavaScript>
Object.setPrototypeOf(myObject, null);
</syntaxhighlight>
 
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using <code>Object.create(null)</code>:
 
<syntaxhighlight lang=JavaScript>
const myObject = Object.create(null);
 
Object.assign(myObject, {
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"J. Random Hacker": "553-1337",
});
</syntaxhighlight>
 
If the property name is a valid identifier, the quotes can be omitted, e.g.:
 
<sourcesyntaxhighlight lang="javascript"JavaScript>
varconst myOtherObject = { foo : 42, bar : false };
</syntaxhighlight>
</source>
 
Lookup is written using property -access notation, either square brackets, which always workswork, or dot notation, which only works for identifier keys:
 
<sourcesyntaxhighlight lang="javascript"JavaScript>
myObject["John Doe"]
myOtherObject.foo
</syntaxhighlight>
</source>
 
You can also loop through all enumerable properties and associated values as follows (a for-in loop):
 
<sourcesyntaxhighlight lang="javascript"JavaScript>
for (varconst property in myObject) {
var const value = myObject[property];
alert console.log("`myObject[" + ${property + "}] = " + ${value}`);
}
</syntaxhighlight>
</source>
 
Or (a for-of loop):
 
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
console.log(`${property} = ${value}`);
}
</syntaxhighlight>
 
A property can be removed as follows:
 
<sourcesyntaxhighlight lang="javascript"JavaScript>
delete myObject["Sally Smart"];
</syntaxhighlight>
</source>
 
As mentioned before, properties are strings. However,and symbols. sinceSince every native object and primitive can be implicitly converted to a string, you can do:
 
<sourcesyntaxhighlight lang="javascript"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>
</source>
 
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.
Any object, including built-in objects such as Array, can be dynamically extended with new properties. For example:
 
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.
<source lang="javascript">
Array.prototype.removeAllObjects = function () {
/* ... */
}
</source>
 
===Julia===
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type is best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, 'for(in)' loops will work as expected on associative 'arrays'. This issue has been drawn into focus by the popularity of JavaScript frameworks that make heavy and sometimes indiscriminate use of prototype to extend JavaScript's inbuilt types.
 
In [[Julia (programming language)|Julia]], the following operations manage associative arrays.
See [http://blog.metawrap.com/blog/June6thIsJavaScriptArrayAndObjectprototypeAwarenessDay.aspx JavaScript Array And Object Prototype Awareness Day] for more information on the issue.
 
Declare dictionary:
=== KornShell 93 (and compliant shells: ksh93, zsh, ...) ===
<syntaxhighlight lang="julia">
phonebook = Dict( "Sally Smart" => "555-9999", "John Doe" => "555-1212", "J. Random Hacker" => "555-1337" )
</syntaxhighlight>
 
Access element:
<!-- Tested in ksh93 r -->
:'''Note:''' ''The latest version of [[Bourne-Again shell|bash]], 3.2, doesn't support associative arrays properly yet.''
 
<syntaxhighlight lang="julia">
Definition:
phonebook["Sally Smart"]
</syntaxhighlight>
 
Add element:
typeset -A phonebook;
<syntaxhighlight lang="julia">
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["J. Random Hacker"]="555-1337");
phonebook["New Contact"] = "555-2222"
</syntaxhighlight>
 
Delete element:
Dereference:
<syntaxhighlight lang="julia">
delete!(phonebook, "Sally Smart")
</syntaxhighlight>
 
Get keys and values as [[Iterator#Implicit iterators|iterables]]:
${phonebook["John Doe"]};
<syntaxhighlight lang="julia">
keys(phonebook)
values(phonebook)
</syntaxhighlight>
 
===KornShell 93, and compliant shells===
=== Lisp ===
In [[Korn Shell|KornShell]] 93, and compliant shells (ksh93, bash4...), the following operations can be used with associative arrays.
[[Lisp programming language|Lisp]] was originally conceived as a "LISt Processing" language, and one of its most important data types is the linked list, which can be treated as an association list ("alist").
 
<!-- Tested in ksh93 r -->
<source lang="lisp">
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");
</syntaxhighlight>
 
Dereference:
<syntaxhighlight lang="ksh">
${phonebook["John Doe"]};
</syntaxhighlight>
 
===Lisp===
[[Lisp programming language|Lisp]] was originally conceived as a "LISt Processing" language, and one of its most important data types is the linked list, which can be treated as an [[association list]] ("alist").
 
<syntaxhighlight lang=Lisp>
'(("Sally Smart" . "555-9999")
("John Doe" . "555-1212")
("J. Random Hacker" . "553-1337"))
</syntaxhighlight>
</source>
 
The syntax <code>(x . y)</code> is used to indicate a [[cons|<code>cons</code>ed]] pair. Keys and values need not be the same type within an alist. Lisp and [[Scheme (programming language)|Scheme]] provide operators such as <code>assoc</code> to manipulate alists in ways similar to associative arrays.
 
A set of operations specific to the handling of association lists exists for [[Common Lisp]], each of these working non-destructively.
Because of their linear nature, alists are used for relatively small sets of data. [[Common Lisp]] also supports a [[hash table]] data type, and for [[Scheme (programming language)|Scheme]] they are implemented in [[SRFI]] 69. Hash tables have greater overhead than alists, but provide much faster access when there are many elements.
 
To add an entry the <code>acons</code> function is employed, creating and returning a new association list. An association list in Common Lisp mimicks a stack, that is, adheres to the last-in-first-out (LIFO) principle, and hence prepends to the list head.
It is easy to construct composite abstract data types in Lisp, using structures and/or the object-oriented programming features, in conjunction with lists, arrays, and hash tables.
 
<syntaxhighlight lang=Lisp>
=== LPC ===
(let ((phone-book NIL))
(setf phone-book (acons "Sally Smart" "555-9999" phone-book))
(setf phone-book (acons "John Doe" "555-1212" phone-book))
(setf phone-book (acons "J. Random Hacker" "555-1337" phone-book)))
</syntaxhighlight>
 
This function can be construed as an 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>
[[LPC (programming language)|LPC]] implements associative arrays as a fundamental type known as either map or mapping, depending on the driver. The keys and values can be of any type. A mapping literal is written as <code>([ key_1 : value_1, key_2 : value_2 ])</code>. Procedural use looks like:
 
<sourcesyntaxhighlight lang="c"Lisp>
;; The effect of
;; (cons (cons KEY VALUE) ALIST)
;; is equivalent to
;; (acons KEY VALUE ALIST)
(let ((phone-book '(("Sally Smart" . "555-9999") ("John Doe" . "555-1212"))))
(cons (cons "J. Random Hacker" "555-1337") phone-book))
</syntaxhighlight>
 
Of course, the destructive <code>push</code> operation also allows inserting entries into an association list, an entry having to constitute a key-value cons in order to retain the mapping's validity.
 
<syntaxhighlight lang=Lisp>
(push (cons "Dummy" "123-4567") phone-book)
</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 leads to a return of the <code>NIL</code> value.
 
<syntaxhighlight lang=Lisp>
(assoc "John Doe" phone-book :test #'string=)
</syntaxhighlight>
 
Two generalizations of <code>assoc</code> exist: <code>assoc-if</code> expects a predicate function that tests each entry's key, returning the first entry for which the predicate produces a non-<code>NIL</code> value upon invocation. <code>assoc-if-not</code> inverts the logic, accepting the same arguments, but returning the first entry generating <code>NIL</code>.
 
<syntaxhighlight lang=Lisp>
;; Find the first entry whose key equals "John Doe".
(assoc-if
#'(lambda (key)
(string= key "John Doe"))
phone-book)
 
;; Finds the first entry whose key is neither "Sally Smart" nor "John Doe"
(assoc-if-not
#'(lambda (key)
(member key '("Sally Smart" "John Doe") :test #'string=))
phone-book)
</syntaxhighlight>
 
The inverse process, the detection of an entry by its value, utilizes <code>rassoc</code>.
 
<syntaxhighlight lang=Lisp>
;; Find the first entry with a value of "555-9999".
;; We test the entry string values with the "string=" predicate.
(rassoc "555-9999" phone-book :test #'string=)
</syntaxhighlight>
 
The corresponding generalizations <code>rassoc-if</code> and <code>rassoc-if-not</code> exist.
 
<syntaxhighlight lang=Lisp>
;; Finds the first entry whose value is "555-9999".
(rassoc-if
#'(lambda (value)
(string= value "555-9999"))
phone-book)
 
;; Finds the first entry whose value is not "555-9999".
(rassoc-if-not
#'(lambda (value)
(string= value "555-9999"))
phone-book)
</syntaxhighlight>
 
All of the previous entry search functions can be replaced by general list-centric variants, such as <code>find</code>, <code>find-if</code>, <code>find-if-not</code>, as well as pertinent functions like <code>position</code> and its derivates.
 
<syntaxhighlight lang=Lisp>
;; Find an entry with the key "John Doe" and the value "555-1212".
(find (cons "John Doe" "555-1212") phone-book :test #'equal)
</syntaxhighlight>
 
Deletion, lacking a specific counterpart, is based upon the list facilities, including destructive ones.
 
<syntaxhighlight lang=Lisp>
;; Create and return an alist without any entry whose key equals "John Doe".
(remove-if
#'(lambda (entry)
(string= (car entry) "John Doe"))
phone-book)
</syntaxhighlight>
 
Iteration is accomplished with the aid of any function that expects a list.
 
<syntaxhighlight lang=Lisp>
;; Iterate via "map".
(map NIL
#'(lambda (entry)
(destructuring-bind (key . value) entry
(format T "~&~s => ~s" key value)))
phone-book)
 
;; Iterate via "dolist".
(dolist (entry phone-book)
(destructuring-bind (key . value) entry
(format T "~&~s => ~s" key value)))
</syntaxhighlight>
 
These being structured lists, processing and transformation operations can be applied without constraints.
 
<syntaxhighlight lang=Lisp>
;; Return a vector of the "phone-book" values.
(map 'vector #'cdr phone-book)
 
;; Destructively modify the "phone-book" via "map-into".
(map-into phone-book
#'(lambda (entry)
(destructuring-bind (key . value) entry
(cons (reverse key) (reverse value))))
phone-book)
</syntaxhighlight>
 
Because of their linear nature, alists are used for relatively small sets of data. [[Common Lisp]] also supports a [[hash table]] data type, and for [[Scheme (programming language)|Scheme]] they are implemented in [[Scheme Requests for Implementation|SRFI]] 69. Hash tables have greater overhead than alists, but provide much faster access when there are many elements. A further characteristic is the fact that Common Lisp hash tables do not, as opposed to association lists, maintain the order of entry insertion.
 
Common Lisp hash tables are constructed via the <code>make-hash-table</code> function, whose arguments encompass, among other configurations, a predicate to test the entry key. While tolerating arbitrary objects, even heterogeneity within a single hash table instance, the specification of this key <code>:test</code> function is confined to distinguishable entities: the Common Lisp standard only mandates the support of <code>eq</code>, <code>eql</code>, <code>equal</code>, and <code>equalp</code>, yet designating additional or custom operations as permissive for concrete implementations.
 
<syntaxhighlight lang=Lisp>
(let ((phone-book (make-hash-table :test #'equal)))
(setf (gethash "Sally Smart" phone-book) "555-9999")
(setf (gethash "John Doe" phone-book) "555-1212")
(setf (gethash "J. Random Hacker" phone-book) "553-1337"))
</syntaxhighlight>
 
The <code>gethash</code> function permits obtaining the value associated with a key.
 
<syntaxhighlight lang=Lisp>
(gethash "John Doe" phone-book)
</syntaxhighlight>
 
Additionally, a default value for the case of an absent key may be specified.
 
<syntaxhighlight lang=Lisp>
(gethash "Incognito" phone-book 'no-such-key)
</syntaxhighlight>
 
An invocation of <code>gethash</code> actually returns two values: the value or substitute value for the key and a boolean indicator, returning <code>T</code> if the hash table contains the key and <code>NIL</code> to signal its absence.
 
<syntaxhighlight lang=Lisp>
(multiple-value-bind (value contains-key) (gethash "Sally Smart" phone-book)
(if contains-key
(format T "~&The associated value is: ~s" value)
(format T "~&The key could not be found.")))
</syntaxhighlight>
 
Use <code>remhash</code> for deleting the entry associated with a key.
 
<syntaxhighlight lang=Lisp>
(remhash "J. Random Hacker" phone-book)
</syntaxhighlight>
 
<code>clrhash</code> completely empties the hash table.
 
<syntaxhighlight lang=Lisp>
(clrhash phone-book)
</syntaxhighlight>
 
The dedicated <code>maphash</code> function specializes in iterating hash tables.
 
<syntaxhighlight lang=Lisp>
(maphash
#'(lambda (key value)
(format T "~&~s => ~s" key value))
phone-book)
</syntaxhighlight>
 
Alternatively, the <code>loop</code> construct makes provisions for iterations, through keys, values, or conjunctions of both.
 
<syntaxhighlight lang=Lisp>
;; Iterate the keys and values of the hash table.
(loop
for key being the hash-keys of phone-book
using (hash-value value)
do (format T "~&~s => ~s" key value))
 
;; Iterate the values of the hash table.
(loop
for value being the hash-values of phone-book
do (print value))
</syntaxhighlight>
 
A further option invokes <code>with-hash-table-iterator</code>, an iterator-creating macro, the processing of which is intended to be driven by the caller.
 
<syntaxhighlight lang=Lisp>
(with-hash-table-iterator (entry-generator phone-book)
(loop do
(multiple-value-bind (has-entry key value) (entry-generator)
(if has-entry
(format T "~&~s => ~s" key value)
(loop-finish)))))
</syntaxhighlight>
 
It is easy to construct composite abstract data types in Lisp, using structures or object-oriented programming features, in conjunction with lists, arrays, and hash tables.
 
===LPC===
[[LPC (programming language)|LPC]] implements associative arrays as a fundamental type known as either "map" or "mapping", depending on the driver. The keys and values can be of any type. A mapping literal is written as <code>([ key_1 : value_1, key_2 : value_2 ])</code>. Procedural code looks like:
 
<syntaxhighlight lang=C>
mapping phone_book = ([]);
phone_book["Sally Smart"] = "555-9999";
phone_book["John Doe"] = "555-1212";
phone_book["J. Random Hacker"] = "555-1337";
</syntaxhighlight>
</source>
 
Mappings are accessed for reading using the indexing operator in the same way as they are for writing, as shown above. So phone_book["Sally Smart"] would return the string "555-9999", and phone_book["John Smith"] would return 0. Testing for presence is done using the function member(), e.g. <code>if(member(phone_book, "John Smith")) write("John Smith is listed.\n");</code>
 
Deletion is accomplished using a function called either m_delete() or map_delete(), depending on the driver, used like: <code>m_delete(phone_book, "Sally Smart");</code>
 
LPC drivers of the "[[LPMud#Amylaar"|Amylaar]] family implement multivalued mappings using a secondary, numeric index. (Driversother drivers of the [[MudOS]] family do not support multivalued mappings.) Example syntax:
 
<sourcesyntaxhighlight lang="c"C>
mapping phone_book = ([:2]);
phone_book["Sally Smart", 0] = "555-9999";
Line 363 ⟶ 1,000:
phone_book["J. Random Hacker", 0] = "555-1337";
phone_book["J. Random Hacker", 1] = "77 Massachusetts Avenue";
</syntaxhighlight>
</source>
 
LPC drivers modern enough to support a foreach() construct use it to iterate through their mapping types.
 
===Lua===
LPC drivers modern enough to support a foreach() construct allow iteration over their mapping types using it.
In [[Lua programming language|Lua]], "table" is a fundamental type that can be used either as an array (numerical index, fast) or as an associative array.
 
The keys and values can be of any type, except nil. The following focuses on non-numerical indexes.
=== Lua ===
In [[Lua programming language|Lua]], table is a fundamental type that can be used either as array (numerical index, fast) or as associative array.
The keys and values can be of any type, except nil. The following with focus on non-numerical indexes.
 
A table literal is written as <code>{ value, key = value, [index] = value, ["non id string"] = value }</code>. For example:
 
<sourcesyntaxhighlight lang="lua"Lua>
phone_book = {
["Sally Smart"] = "555-9999",
Line 387 ⟶ 1,025:
-- Table and function (and other types) can also be used as keys
}
</syntaxhighlight>
</source>
 
If the key is a valid identifier (not a keywordreserved word), the quotes can be omitted. TheyIdentifiers are case sensitive.
 
Lookup is written using either square brackets, which always works, or dot notation, which only works for identifier keys:
 
<sourcesyntaxhighlight lang="lua"Lua>
print(aTable["John Doe"](45))
x = aTable.subTable.k
</syntaxhighlight>
</source>
 
You can also loop through all keys and associated values with iterators or for -loops:
 
<sourcesyntaxhighlight lang="lua"Lua>
simple = { [true] = 1, [false] = 0, [3.14] = math.pi, x = 'x', ["!"] = 42 }
function FormatElement(key, value)
Line 416 ⟶ 1,054:
until k == nil
print""
</syntaxhighlight>
</source>
 
An entry can be removed by setting it to nil:
 
<sourcesyntaxhighlight lang="lua"Lua>
simple.x = nil
</syntaxhighlight>
</source>
 
Likewise, you can overwrite values or add them:
 
<sourcesyntaxhighlight lang="lua"Lua>
simple['%'] = "percent"
simple['!'] = 111
</syntaxhighlight>
</source>
 
===Mathematica and Wolfram Language===
=== MUMPS ===
 
[[Mathematica]] and [[Wolfram Language]] use the Association expression to represent associative arrays.<ref>{{cite web|url=https://reference.wolfram.com/language/ref/Association.html|title=Association (<-...->)—Wolfram Language Documentation|website=reference.wolfram.com}}</ref>
 
<syntaxhighlight lang="mathematica">
phonebook = <| "Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337" |>;
</syntaxhighlight>
 
To access:<ref>{{cite web|url=https://reference.wolfram.com/language/ref/Key.html|title=Key—Wolfram Language Documentation|website=reference.wolfram.com}}</ref>
 
<syntaxhighlight lang="mathematica">
phonebook[[Key["Sally Smart"]]]
</syntaxhighlight>
 
If the keys are strings, the Key keyword is not necessary, so:
 
<syntaxhighlight lang="mathematica">
phonebook[["Sally Smart"]]
</syntaxhighlight>
 
To list keys:<ref>{{cite web|url=https://reference.wolfram.com/language/ref/Keys.html|title=Keys—Wolfram Language Documentation|website=reference.wolfram.com}}</ref> and values<ref>{{cite web|url=https://reference.wolfram.com/language/ref/Values.html|title=Values—Wolfram Language Documentation|website=reference.wolfram.com}}</ref>
 
Keys[phonebook]
Values[phonebook]
 
===MUMPS===
In [[MUMPS]] every array is an associative array. The built-in, language-level, direct support for associative arrays
applies to private, process-specific arrays stored in memory called "locals" as well as to the permanent, shared, global arrays stored on disk which are available concurrently byto multiple jobs. The name for globals is preceded by the circumflex "^" to distinquishdistinguish itthem from local variable namesvariables.
 
SET ^phonebook("Sally Smart")="555-9999" ;; storing permanent data
SET phonebook("John Doe")="555-1212" ;; storing temporary data
SET phonebook("J. Random Hacker")="553-1337" ;; storing temporary data
MERGE ^phonebook=phonebook ;; copying temporary data into permanent data
 
To accessAccessing the value of an element, simply requires using the name with the subscript:
 
WRITE "Phone Number :",^phonebook("Sally Smart"),!
Line 446 ⟶ 1,111:
You can also loop through an associated array as follows:
 
SET NAME=""
FOR S NAME=$ORDER(^phonebook(NAME)) QUIT:NAME="" WRITE NAME," Phone Number :",^phonebook(NAME),!
 
===Objective-C OCaml(Cocoa/GNUstep) ===
[[Cocoa (API)|Cocoa]] and [[GNUstep]], written in [[Objective-C]], handle associative arrays using <code>NSMutableDictionary</code> (a mutable version of <code>NSDictionary</code>) class cluster. This class allows assignments between any two objects. A copy of the key object is made before it is inserted into <code>NSMutableDictionary</code>, therefore the keys must conform to the <code>NSCopying</code> protocol. When being inserted to a dictionary, the value object receives a retain message to increase its reference count. The value object will receive the release message when it will be deleted from the dictionary (either explicitly or by adding to the dictionary a different object with the same key).
 
<syntaxhighlight lang=ObjC>
NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] init];
[aDictionary setObject:@"555-9999" forKey:@"Sally Smart"];
[aDictionary setObject:@"555-1212" forKey:@"John Doe"];
[aDictionary setObject:@"553-1337" forKey:@"Random Hacker"];
</syntaxhighlight>
 
To access assigned objects, this command may be used:
 
<syntaxhighlight lang=ObjC>
id anObject = [aDictionary objectForKey:@"Sally Smart"];
</syntaxhighlight>
 
All keys or values can be enumerated using <code>NSEnumerator</code>:
 
<syntaxhighlight lang=ObjC>
NSEnumerator *keyEnumerator = [aDictionary keyEnumerator];
id key;
while ((key = [keyEnumerator nextObject]))
{
// ... process it here ...
}
</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>
for (id key in aDictionary) {
// ... process it here ...
}
</syntaxhighlight>
 
What is even more practical, structured data graphs may be easily created using [[Cocoa (API)|Cocoa]], especially <code>NSDictionary</code> (<code>NSMutableDictionary</code>). This can be illustrated with this compact example:
 
<syntaxhighlight lang=ObjC>
NSDictionary *aDictionary =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjectsAndKeys:
@"555-9999", @"Sally Smart",
@"555-1212", @"John Doe",
nil], @"students",
[NSDictionary dictionaryWithObjectsAndKeys:
@"553-1337", @"Random Hacker",
nil], @"hackers",
nil];
</syntaxhighlight>
 
Relevant fields can be quickly accessed using key paths:
 
<syntaxhighlight lang=ObjC>
id anObject = [aDictionary valueForKeyPath:@"students.Sally Smart"];
</syntaxhighlight>
 
===OCaml===
The [[OCaml]] programming language provides three different associative containers. The simplest is a list of pairs:
 
<sourcesyntaxhighlight lang="ocaml"OCaml>
# let m = [
"Sally Smart", "555-9999";
Line 464 ⟶ 1,185:
# List.assoc "John Doe" m;;
- : string = "555-1212"
</syntaxhighlight>
</source>
 
The second is a polymorphic hash table:
 
<sourcesyntaxhighlight lang="ocaml"OCaml>
# let m = Hashtbl.create 3;;
val m : ('_a, '_b) Hashtbl.t = <abstr>
Line 477 ⟶ 1,198:
# Hashtbl.find m "John Doe";;
- : string = "555-1212"
</syntaxhighlight>
</source>
 
The code above uses OCaml's default hash function <code>Hashtbl.hash</code>, which is defined automatically for all types. To use a modified hash function, use the functor interface <code>Hashtbl.Make</code> to create a module, such as with <code>Map</code>.
 
Finally, functional maps (represented as immutable balanced binary trees):
 
<sourcesyntaxhighlight lang="ocaml"OCaml>
# includemodule StringMap = (Map.Make(String));;
...
# let m = StringMap.add "Sally Smart" "555-9999" StringMap.empty
let m = StringMap.add "John Doe" "555-1212" m
let m = StringMap.add "J. Random Hacker" "553-1337" m;;
val m : string StringMap.t = <abstr>
# StringMap.find "John Doe" m;;
- : string = "555-1212"
</syntaxhighlight>
</source>
 
Note that in order to use <code>Map</code>, you have to provide the functor <code>Map.Make</code> with a module which defines the key type and the comparison function. The third-party library ExtLib provides a polymorphic version of functional maps, called <code>PMap</code>,<ref>{{cite web |title=Module PMap |url=http://ocaml-extlib.googlecode.com/svn/doc/apiref/PMap.html |date=2008 |archive-url=https://web.archive.org/web/20081211233540/http://ocaml-extlib.googlecode.com/svn/doc/apiref/PMap.html |archive-date=11 December 2008 |website=Ocaml-extlib |access-date=3 August 2020}}</ref> which is given a comparison function upon creation.
Lists of pairs and functional maps both provide a purely functional interface. In contrast, hash tables provide an imperative interface. For many operations, hash tables are significantly faster than lists of pairs and functional maps.
 
Lists of pairs and functional maps both provide a purely functional interface. By contrast, hash tables provide an imperative interface. For many operations, hash tables are significantly faster than lists of pairs and functional maps.
=== Perl ===
[[Perl]] has built-in, language-level support for associative arrays. Modern Perl vernacular refers to associative arrays as ''hashes''; the term ''associative array'' is found in older documentation, but is considered somewhat archaic. Perl hashes are flat: keys are strings and values are scalars. However, values may be [[reference (computer science)|references]] to arrays or other hashes, and the standard Perl module Tie::RefHash enables hashes to be used with reference keys.
 
===OptimJ===
A hash variable is marked by a <code>%</code> [[sigil (computer programming)|sigil]], to distinguish it from scalar, array and other data types. A hash literal is a key-value list, with the preferred form using Perl's <code>=&gt;</code> token, which is mostly semantically identical to the comma and makes the key-value association clearer:
{{More citations needed section|date=February 2011}}
The [[OptimJ]] programming language is an extension of Java 5. As does Java, Optimj provides maps; but OptimJ also provides true associative arrays. Java arrays are indexed with non-negative integers; associative arrays are indexed with any type of key.
 
<sourcesyntaxhighlight lang="perl"Java>
String[String] phoneBook = {
%phone_book = (
' "Sally Smart'" = -> '"555-9999'",
' "John Doe'" = -> '"555-1212'",
"J. Random Hacker" -> "553-1337"
};
 
// String[String] is not a java type but an optimj type:
// associative array of strings indexed by strings.
 
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
 
// The previous statement prints: "555-9999" "555-1212" "553-1337"
 
// 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)
// i.e. phoneBook["John Doe"] returns "555-1212"
 
</syntaxhighlight>
 
Of course, it is possible to define multi-dimensional arrays, to mix Java arrays and associative arrays, to mix maps and associative arrays.
 
<syntaxhighlight lang=Java>
int[String][][double] a;
java.util.Map<String[Object], Integer> b;
</syntaxhighlight>
 
===Perl 5===
[[Perl 5]] has built-in, language-level support for associative arrays. Modern Perl refers to associative arrays as ''hashes''; the term ''associative array'' is found in older documentation but is considered somewhat archaic. Perl 5 hashes are flat: keys are strings and values are scalars. However, values may be [[reference (computer science)|references]] to arrays or other hashes, and the standard Perl 5 module Tie::RefHash enables hashes to be used with reference keys.
 
A hash variable is marked by a <code>%</code> [[sigil (computer programming)|sigil]], to distinguish it from scalar, array, and other data types. A hash literal is a key-value list, with the preferred form using Perl's <code>=&gt;</code> token, which is semantically mostly identical to the comma and makes the key-value association clearer:
 
<syntaxhighlight lang=Perl>
my %phone_book = (
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '553-1337',
);
</syntaxhighlight>
</source>
 
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> the key is surrounded by ''[[Bracket#Curly 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:
 
<sourcesyntaxhighlight lang="perl"Perl>
foreach $name (keys %phone_book) {
print $name, "\n";
}
</syntaxhighlight>
</source>
 
One can iterate through (key, value) pairs using the <code>each</code> function:
 
<sourcesyntaxhighlight lang="perl"Perl>
while (($name, $number) = each %phone_book) {
print 'Number for ', $name, ': ', $number, "\n";
}
</syntaxhighlight>
</source>
 
A hash ''"reference''", which is a scalar value that points to a hash, is specified in literal form using curly braces as delimiters, with syntax otherwise similar to specifying a hash literal:
 
<sourcesyntaxhighlight lang="perl"Perl>
my $phone_book = {
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '553-1337',
};
</syntaxhighlight>
</source>
 
Values in a hash reference are accessed using the dereferencing operator:
 
<sourcesyntaxhighlight lang="perl"Perl>
print $phone_book->{'Sally Smart'};
</syntaxhighlight>
</source>
 
When the hash contained in the hash reference needs to be referred to as a whole, as with the <code>keys</code> function, the syntax is as follows:
 
<sourcesyntaxhighlight lang="perl"Perl>
foreach $name (keys %{$phone_book}) {
print 'Number for ', $name, ': ', $phone_book->{$name}, "\n";
}
</syntaxhighlight>
</source>
 
===Perl 6 (Raku)===
=== PHP ===<!-- This section is linked from [[PHP]] -->
[[Raku (programming language)|Perl 6]], renamed as "Raku", also has built-in, language-level support for associative arrays, which are referred to as ''hashes'' or as objects performing the "associative" role. As in Perl 5, Perl 6 default hashes are flat: keys are strings and values are scalars. One can define a hash to not coerce all keys to strings automatically: these are referred to as "object hashes", because the keys of such hashes remain the original object rather than a stringification thereof.
[[PHP]]'s built-in array type is in reality an associative array. Even when using numerical indexes, PHP internally stores it as an associative array.<ref>About the implementation of [http://se.php.net/manual/en/language.types.array.php Arrays] in PHP</ref> This is why one in PHP can have non-consecutive numerically indexed arrays. The keys have to be scalar values (string, floating point number or integer), 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.
 
A hash variable is typically marked by a <code>%</code> [[sigil (computer programming)|sigil]], to visually distinguish it from scalar, array, and other data types, and to define its behaviour towards iteration. A hash literal is a key-value list, with the preferred form using Perl's <code>=&gt;</code> token, which makes the key-value association clearer:
An associative array can be formed in one of two ways:
 
<sourcesyntaxhighlight lang="php"Perl6>
my %phone-book =
$phonebook = array ();
$phonebook[ 'Sally Smart'] => '555-9999';,
$phonebook[ 'John Doe'] => '555-1212';,
'J. Random Hacker' => '553-1337',
;
</syntaxhighlight>
 
Accessing a hash element uses the syntax <code>%hash_name{$key}</code> – the key is surrounded by curly braces and the hash name (note that the sigil does '''not''' change, contrary to Perl 5). The value of <code>%phone-book{'John Doe'}</code> is <code>'555-1212'</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:
 
<syntaxhighlight lang=Perl6>
for %phone-book.keys -> $name {
say $name;
}
</syntaxhighlight>
 
By default, when iterating through a hash, one gets key–value pairs.
 
<syntaxhighlight lang=Perl6>
for %phone-book -> $entry {
say "Number for $entry.key(): $entry.value()"; # using extended interpolation features
}
</syntaxhighlight>
 
It is also possible to get alternating key values and value values by using the <code>kv</code> method:
 
<syntaxhighlight lang=Perl6>
for %phone-book.kv -> $name, $number {
say "Number for $name: $number";
}
</syntaxhighlight>
 
Raku doesn't have any references. Hashes can be passed as single parameters that are not flattened. If you want to make sure that a subroutine only accepts hashes, use the ''%'' sigil in the Signature.
 
<syntaxhighlight lang=Perl6>
sub list-phone-book(%pb) {
for %pb.kv -> $name, $number {
say "Number for $name: $number";
}
}
list-phone-book(%phone-book);
</syntaxhighlight>
 
In compliance with [[gradual typing]], hashes may be subjected to type constraints, confining a set of valid keys to a certain type.
 
<syntaxhighlight lang=Perl6>
# Define a hash whose keys may only be integer numbers ("Int" type).
my %numbersWithNames{Int};
 
# Keys must be integer numbers, as in this case.
%numbersWithNames.push(1 => "one");
 
# This will cause an error, as strings as keys are invalid.
%numbersWithNames.push("key" => "two");
</syntaxhighlight>
 
===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:
 
<syntaxhighlight lang="php">
$phonebook = array();
$phonebook['Sally Smart'] = '555-9999';
$phonebook['John Doe'] = '555-1212';
$phonebook['J. Random Hacker'] = '555-1337';
 
// or
 
$phonebook = array (
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '555-1337',
);
 
// or, as of PHP 5.4
 
$phonebook = [
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '555-1337',
];
 
// or
 
$phonebook['contacts']['Sally Smart']['number'] = '555-9999';
$phonebook['contacts']['JohnSally DoeSmart']['number'] = '555-12129999';
$phonebook['contacts']['John Doe']['number'] = '555-1212';
$phonebook['contacts']['J. Random Hacker']['number'] = '555-1337';
</syntaxhighlight>
</source>
 
YouPHP can also loop through an associative array as follows:
 
<sourcesyntaxhighlight lang="php">
foreach ($phonebook as $name => $number) {
echo "'Number for ', $name, ': ', $number, "\n";
}
 
// For the last array example it is used like this
foreach ($phonebook['contacts'] as $name => $num) {
echo 'Name: ', $name, ', number: ', $num['number'], "\n";
{
echo "<div>Name:{$name}</div>";
echo "<div>Number:{$num['number']}</div>";
}
</syntaxhighlight>
</source>
 
PHP has an extensive set of functions to operate on arrays.<ref>{{cite web |title=Arrays |url=https://www.php.net/manual/en/language.types.array.php |website=PHP.net |access-date=3 August 2020}}</ref>
 
Associative arrays that can use objects as keys, instead of strings and integers, can be implemented with the <code>SplObjectStorage</code> class from the Standard PHP Library (SPL).<ref>{{cite web |title=The SplObjectStorage class |url=http://php.net/SplObjectStorage |website=PHP.net |access-date=3 August 2020}}</ref>
PHP has an [http://php.net/array extensive set of functions] to operate on arrays.
 
=== Pike ===
[[Pike (programming language)|Pike]] has built-in support for Associativeassociative Arraysarrays, which are referred to as mappings. Mappings are created as follows:
 
<sourcesyntaxhighlight lang="textpike">
mapping(string:string) phonebook = ([
"Sally Smart":"555-9999",
Line 600 ⟶ 1,434:
"J. Random Hacker":"555-1337"
]);
</syntaxhighlight>
</source>
 
Accessing and testing for presence in mappings is done using the indexing operator. So <code>phonebook["Sally Smart"]</code> would return the string <code>"555-9999"</code>, and <code>phonebook["John Smith"]</code> would return 0.
 
Iterating through a mapping can be done using either <code>foreach</code>:
 
<sourcesyntaxhighlight lang="textpike">
foreach(phonebook; string key; string value) {
write("%s:%s\n", key, value);
}
</syntaxhighlight>
</source>
 
Or using an iterator object:
 
<sourcesyntaxhighlight lang="textpike">
Mapping.Iterator i = get_iterator(phonebook);
while (i->index()) {
Line 620 ⟶ 1,454:
i->next();
}
</syntaxhighlight>
</source>
 
Elements of a mapping can be removed using <code>m_delete</code>, which returns the value of the removed index:
 
<sourcesyntaxhighlight lang="textpike">
string sallys_number = m_delete(phonebook, "Sally Smart");
</syntaxhighlight>
</source>
 
=== PostScript ===
In [[PostScript]], associative arrays are called dictionaries. In Level 1 PostScript they must be created explicitly, but Level 2 introduced direct declaration using thea double-braceangled-bracket syntax:
 
<syntaxhighlight lang="postscript">
<code>
% Level 1 declaration
3 dict dup begin
Line 638 ⟶ 1,472:
/blue (bleu) def
end
 
% Level 2 declaration
<<
Line 645 ⟶ 1,479:
/blue (blau)
>>
% Both methods leave the dictionary on the operand stack</code>
 
Dictionaries can be% accessedBoth directlymethods using '''get''' or implicitly by placingleave the dictionary on the dictionaryoperand stack using '''begin''':
</syntaxhighlight>
 
Dictionaries can be accessed directly, using <code>get</code>, or implicitly, by placing the dictionary on the dictionary stack using <code>begin</code>:
<code>
 
<syntaxhighlight lang="postscript">
% With the previous two dictionaries still on the operand stack
/red get print % outputs 'rot'
 
begin
green print % outputs 'vert'
end</code>
</syntaxhighlight>
 
Dictionary contents can be iterated through using '''<code>forall'''</code>, though not in any particular order:
 
<syntaxhighlight lang="postscript">
<code>
% Level 2 example
<<
Line 666 ⟶ 1,502:
/That 2
/Other 3
>> {exch =print ( is ) print ==} forall</code>
</syntaxhighlight>
May well output:
 
<code>
Which may output:
 
<syntaxhighlight lang="postscript">
That is 2
This is 1
Other is 3</code>
</syntaxhighlight>
 
Dictionaries can be augmented (up to their defined size only in Level 1) or altered using '''<code>put'''</code>, and entries can be removed using '''<code>undef'''</code>:
<syntaxhighlight lang="postscript">
<code>
% define a dictionary for easy reuse:
/MyDict <<
Line 680 ⟶ 1,520:
/vert (gruen)
>> def
 
% add to it
MyDict /bleu (blue) put
 
% change it
MyDict /vert (green) put
 
% remove something
MyDict /rouge undef</code>
</syntaxhighlight>
 
=== PythonProlog ===
In [[Python (programming language)|Python]], associative arrays are called ''[[Python syntax and semantics#Collection types|dictionaries]]''. Dictionary literals are marked with curly braces:
 
Some versions of [[Prolog]] include dictionary ("dict") utilities.<ref>[http://www.swi-prolog.org/pldoc/man?section=dicts "Dicts: structures with named arguments"]</ref>
<source lang="python">
 
===Python===
In [[Python (programming language)|Python]], associative arrays are called "[[Python syntax and semantics#Collection types|dictionaries]]". Dictionary literals are delimited by curly braces:
 
<syntaxhighlight lang="python">
phonebook = {
' "Sally Smart' ": '"555-9999'",
' "John Doe' ": '"555-1212'",
' "J. Random Hacker' ": '"553-1337'",
}
</syntaxhighlight>
</source>
 
Dictionary items can be accessed using the array indexing operator:
To access an entry in Python simply use the array indexing operator. For example, the expression <code>phonebook['Sally Smart']</code> would return <code>'555-9999'</code>.
<syntaxhighlight lang="python">
>>> phonebook["Sally Smart"]
'555-9999'
</syntaxhighlight>
 
An example loopLoop [[iterator#Python|iterating]] through all the keys of the dictionary:
 
<sourcesyntaxhighlight lang="python">
>>> for key in phonebook:
print... print(key, phonebook[key])
Sally Smart 555-9999
</source>
J. Random Hacker 553-1337
John Doe 555-1212
</syntaxhighlight>
 
Iterating through (key, value) tuples:
 
<sourcesyntaxhighlight lang="python">
>>> for key, value in phonebook.iteritemsitems():
print... print(key, value)
Sally Smart 555-9999
</source>
J. Random Hacker 553-1337
John Doe 555-1212
</syntaxhighlight>
 
Dictionary keys can be individually deleted using the <code>del</code> statement. The corresponding value can be returned before the key-value pair is deleted using the "pop" method of "dict" type:
Dictionaries can also be constructed with the <code>dict</code> builtin, which is most commonly found inside list comprehensions and generator expressions, and it takes a key-value list:
 
<sourcesyntaxhighlight lang="python">
>>> del phonebook["John Doe"]
dict((key, value) for key, value in phonebook.items() if 'J' in key)
>>> val = phonebook.pop("Sally Smart")
</source>
>>> phonebook.keys() # Only one key left
['J. Random Hacker']
</syntaxhighlight>
 
Python 2.7 and 3.x also support [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">
>>> square_dict = {i: i*i for i in range(5)}
>>> square_dict
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> {key: value for key, value in phonebook.items() if "J" in key}
{'J. Random Hacker': '553-1337', 'John Doe': '555-1212'}
</syntaxhighlight>
 
Strictly speaking, a dictionary is a super-set of an associative array, since neither the keys or values are limited to a single datatype. One could think of a dictionary as an "associative list" using the nomenclature of Python. For example, the following is also legitimate:
 
<syntaxhighlight lang="python">
phonebook = {
"Sally Smart": "555-9999",
"John Doe": None,
"J. Random Hacker": -3.32,
14: "555-3322",
}
</syntaxhighlight>
 
The dictionary keys must be of an [[Immutable object|immutable]] data type. In Python, strings are immutable due to their method of implementation.
 
===Red===
In [[Red (programming language)|Red]] the built-in <code>map!</code><ref>{{cite web|url=https://doc.red-lang.org/en/datatypes/map.html|title=Map! datatype|website=doc.red-lang.org}}</ref> datatype provides an associative array that maps values of word, string, and scalar key types to values of any type. A hash table is used internally for lookup.
 
A map can be written as a literal, such as <code>#(key1 value1 key2 value2 ...)</code>, or can be created using <code>make map! [key1 value1 key2 value2 ...]</code>:
 
<syntaxhighlight lang="red">
Red [Title:"My map"]
 
my-map: make map! [
"Sally Smart" "555-9999"
"John Doe" "555-1212"
"J. Random Hacker" "553-1337"
]
 
; Red preserves case for both keys and values, however lookups are case insensitive by default; it is possible to force case sensitivity using the <code>/case</code> refinement for <code>select</code> and <code>put</code>.
 
; It is of course possible to use <code>word!</code> values as keys, in which case it is generally preferred to use <code>set-word!</code> values when creating the map, but any word type can be used for lookup or creation.
 
my-other-map: make map! [foo: 42 bar: false]
 
; Notice that the block is not reduced or evaluated in any way, therefore in the above example the key <code>bar</code> is associated with the <code>word!</code> <code>false</code> rather than the <code>logic!</code> value false; literal syntax can be used if the latter is desired:
 
my-other-map: make map! [foo: 42 bar: #[false]]
 
; or keys can be added after creation:
 
my-other-map: make map! [foo: 42]
my-other-map/bar: false
 
; Lookup can be written using <code>path!</code> notation or using the <code>select</code> action:
 
select my-map "Sally Smart"
my-other-map/foo
 
; You can also loop through all keys and values with <code>foreach</code>:
 
foreach [key value] my-map [
print [key "is associated to" value]
]
 
; A key can be removed using <code>remove/key</code>:
Dictionary keys can be individually deleted using the del statement. The corresponding value can be returned before the key-value pair are deleted using the pop method of dict types;
 
remove/key my-map "Sally Smart"
<source lang="python">
</syntaxhighlight>
del phonebook['John Doe']
val = phonebook.pop('Sally Smart')
assert phonebook.keys() == ['J. Random Hacker'] # Only one key left
</source>
 
=== REXX ===
In [[REXX]], associative arrays are called ''Stem"stem variables''" or ''"Compound variables''".
 
<sourcesyntaxhighlight lang="textrexx">
KEY = 'Sally Smart'
PHONEBOOK.KEY = '555-9999'
KEY = 'John Doe'
PHONEBOOK.KEY = '555-1212'
KEY = 'J. RamdonRandom Hacker'
PHONEBOOK.KEY = '553-1337'
</syntaxhighlight>
</source>
 
Stem variables with numeric keys typically start at 1 and go up from there. The 0 -key stem variable
is used (by convention) ascontains the counttotal number of items in the whole stem.:
 
<sourcesyntaxhighlight lang="textrexx">
NAME.1 = 'Sally Smart'
NAME.2 = 'John Doe'
NAME.3 = 'J. Random Hacker'
NAME.0 = 3
</syntaxhighlight>
</source>
 
[[REXX]] has no easy way of automatically accessing the keys forof a stem variable; and typically the
keys are stored in a separate associative array, with numeric keys.
 
=== Ruby ===<!-- This section is linked from [[
In [[Ruby programming language|Ruby]] a hash table is used as follows:
Constructing and using a [[hash table
Ruby (programming language)]] -->
 
<syntaxhighlight lang="rb">
In [[Ruby programming language|Ruby]] a Hash is used as follows:
 
<source lang="ruby">
phonebook = {
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
'J. Random Hacker' => '553-1337'
}
phonebook['John Doe']
</source>
</syntaxhighlight>
 
Ruby supports hash looping and iteration with the following syntax:
<code>phonebook['John Doe']</code> produces <code>'555-1212'</code>
 
<syntaxhighlight lang="irb">
To iterate over the hash, use something like the following:
irb(main):007:0> ### iterate over keys and values
irb(main):008:0* phonebook.each {|key, value| puts key + " => " + value}
Sally Smart => 555-9999
John Doe => 555-1212
J. Random Hacker => 553-1337
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):009:0> ### iterate keys only
irb(main):010:0* phonebook.each_key {|key| puts key}
Sally Smart
John Doe
J. Random Hacker
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
irb(main):011:0> ### iterate values only
irb(main):012:0* phonebook.each_value {|value| puts value}
555-9999
555-1212
553-1337
=> {"Sally Smart"=>"555-9999", "John Doe"=>"555-1212", "J. Random Hacker"=>"553-1337"}
</syntaxhighlight>
 
Ruby also supports many other useful operations on hashes, such as merging hashes, selecting or rejecting elements that meet some criteria, inverting (swapping the keys and values), and flattening a hash into an array.
<source lang="ruby">
phonebook.each {|key, value| puts key + " => " + value}
</source>
 
===Rust===
Additionally, each key may be shown individually:
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.
 
<sourcesyntaxhighlight lang="rubyrust">
use std::collections::HashMap;
phonebook.each_key {|key| puts key}
let mut phone_book = HashMap::new();
</source>
phone_book.insert("Sally Smart", "555-9999");
phone_book.insert("John Doe", "555-1212");
phone_book.insert("J. Random Hacker", "555-1337");
</syntaxhighlight>
 
The default iterators visit all entries as tuples. The <code>HashMap</code> iterators visit entries in an unspecified order and the <code>BTreeMap</code> iterator visits entries in the order defined by the key type.
Each value may, of course, also be shown:
<syntaxhighlight lang="rust">
for (name, number) in &phone_book {
println!("{} {}", name, number);
}
</syntaxhighlight>
 
There is also an iterator for keys:
<source lang="ruby">
<syntaxhighlight lang="rust">
phonebook.each_value {|value| puts value}
for name in phone_book.keys() {
</source>
println!("{}", name);
}
</syntaxhighlight>
 
=== S-Lang ===
[[S-Lang (programming language)|S-Lang]] has an associative array type.:
 
For example:
 
<sourcesyntaxhighlight lang="Ctext">
phonebook = Assoc_Type[];
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
phonebook["J. Random Hacker"] = "555-1337"
</syntaxhighlight>
</source>
 
You can also loop through an associated array in a number of ways.:
Here is one
 
<sourcesyntaxhighlight lang="Ctext">
foreach name (phonebook) {
vmessage ("%s %s", name, phonebook[name]);
}
</syntaxhighlight>
</source>
 
To print a sorted-list, it is better to take advantage of S-lang's strong
support for standard arrays:
 
<sourcesyntaxhighlight lang="Ctext">
keys = assoc_get_keys(phonebook);
i = array_sort(keys);
vals = assoc_get_values(phonebook);
array_map (Void_Type, &vmessage, "%s %s", keys[i], vals[i]);
</syntaxhighlight>
</source>
 
=== Smalltalk Scala===
[[Scala (programming language)|Scala]] provides an immutable <code>Map</code> class as part of the <code>scala.collection</code> framework:
In [[Smalltalk]] a dictionary is used:
 
<sourcesyntaxhighlight lang="smalltalkscala">
val phonebook = Map("Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337")
</syntaxhighlight>
 
Scala's [[type inference]] will decide that this is a <code>Map[String, String]</code>. To access the array:
 
<syntaxhighlight lang="scala">
phonebook.get("Sally Smart")
</syntaxhighlight>
 
This returns an <code>Option</code> type, Scala's equivalent of the [[Monad (functional programming)#The Maybe monad|Maybe monad]] in Haskell.
 
===Smalltalk===
In [[Smalltalk]] a <code>Dictionary</code> is used:
 
<syntaxhighlight lang="smalltalk">
phonebook := Dictionary new.
phonebook at: 'Sally Smart' put: '555-9999'.
phonebook at: 'John Doe' put: '555-1212'.
phonebook at: 'J. Random Hacker' put: '553-1337'.
</syntaxhighlight>
</source>
 
To access an entry the message <code>#at:</code> is sent to the dictionary object.:
 
<sourcesyntaxhighlight lang="smalltalk">
phonebook at: 'Sally Smart'
</syntaxhighlight>
</source>
 
Which gives:
 
<sourcesyntaxhighlight lang="text">
'555-9999'
</syntaxhighlight>
</source>
 
A dictionary hashes, or compares, based on equality and marks both key and value as
=== SNOBOL ===
[[Garbage collection (computer science)#Strong and weak references|strong references]]. Variants exist in which hash/compare on identity (IdentityDictionary) or keep [[Garbage collection (computer science)#Strong and weak references|weak references]] (WeakKeyDictionary / WeakValueDictionary).
[[SNOBOL]] is one of the first (if not the first) programming languages to use associative arrays.
Because every object implements #hash, any object can be used as key (and of course also as value).
Associative arrays in [[SNOBOL]] are called Tables.
 
===SNOBOL===
<source lang="text">
[[SNOBOL]] is one of the first (if not the first) programming languages to use associative arrays. Associative arrays in SNOBOL are called Tables.
 
<syntaxhighlight lang="snobol">
PHONEBOOK = TABLE()
PHONEBOOK['Sally Smart'] = '555-9999'
PHONEBOOK['John Doe'] = '555-1212'
PHONEBOOK['J. Random Hacker'] = '553-1337'
</syntaxhighlight>
</source>
 
===Standard TCL ML===
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.
In [[Tcl]] every array is an associative array.
 
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–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>.
<source lang="tcl">
set "phonebook(Sally Smart)" 555-9999
set "phonebook(John Doe)" 555-1212
set "phonebook(J. Random Hacker)" 553-1337
</source>
 
<syntaxhighlight lang="sml">
The first argument of the <code>set</code> command has to be enclosed by double quotes, as it contains a space. In Tcl, space is used to separate arguments. Alternatively, array setting can be grouped into a single command (keys braced because they contain whitespace):
- structure StringMap = BinaryMapFn (struct
type ord_key = string
val compare = String.compare
end);
structure StringMap : ORD_MAP
 
- val m = StringMap.insert (StringMap.empty, "Sally Smart", "555-9999")
<source lang="tcl">
val m = StringMap.insert (m, "John Doe", "555-1212")
array set phonebook {
val m = StringMap.insert (m, "J. Random Hacker", "553-1337");
{Sally Smart} 555-9999
val m =
{John Doe} 555-1212
T
{J. Random Hacker} 553-1337
{cnt=3,key="John Doe",
}
left=T {cnt=1,key="J. Random Hacker",left=E,right=E,value="553-1337"},
</source>
right=T {cnt=1,key="Sally Smart",left=E,right=E,value="555-9999"},
value="555-1212"} : string StringMap.map
- StringMap.find (m, "John Doe");
val it = SOME "555-1212" : string option
</syntaxhighlight>
 
SML/NJ also provides a polymorphic hash table:
To access an entry and put it on standard output
 
<sourcesyntaxhighlight lang="tclsml">
- exception NotFound;
puts "$phonebook(Sally Smart)"
exception NotFound
</source>
- val m : (string, string) HashTable.hash_table = HashTable.mkTable (HashString.hashString, op=) (3, NotFound);
val m =
HT
{eq_pred=fn,hash_fn=fn,n_items=ref 0,not_found=NotFound(-),
table=ref [|NIL,NIL,NIL,NIL,NIL,NIL,NIL,NIL,NIL,NIL,NIL,NIL,...|]}
: (string,string) HashTable.hash_table
- HashTable.insert m ("Sally Smart", "555-9999");
val it = () : unit
- HashTable.insert m ("John Doe", "555-1212");
val it = () : unit
- HashTable.insert m ("J. Random Hacker", "553-1337");
val it = () : unit
HashTable.find m "John Doe"; (* returns NONE if not found *)
val it = SOME "555-1212" : string option
- HashTable.lookup m "John Doe"; (* raises the exception if not found *)
val it = "555-1212" : string
</syntaxhighlight>
 
Monomorphic hash tables are also supported, using the <code>HashTableFn</code> functor.
The result is here
 
Another Standard ML implementation, [[Moscow ML]], also provides some associative containers. First, it provides polymorphic hash tables in the <code>Polyhash</code> structure. Also, some functional maps from the SML/NJ library above are available as <code>Binarymap</code>, <code>Splaymap</code>, and <code>Intmap</code> structures.
<source lang="text">
 
===Tcl===
There are two [[Tcl]] facilities that support associative-array semantics. An "array" is a collection of variables. A "dict" is a full implementation of associative arrays.
 
====array====
<syntaxhighlight lang=Tcl>
set {phonebook(Sally Smart)} 555-9999
set john {John Doe}
set phonebook($john) 555-1212
set {phonebook(J. Random Hacker)} 553-1337
</syntaxhighlight>
 
If there is a space character in the variable name, the name must be grouped using either curly brackets (no substitution performed) or double quotes (substitution is performed).
 
Alternatively, several array elements can be set by a single command, by presenting their mappings as a list (words containing whitespace are braced):
 
<syntaxhighlight lang=Tcl>
array set phonebook [list {Sally Smart} 555-9999 {John Doe} 555-1212 {J. Random Hacker} 553-1337]
</syntaxhighlight>
 
To access one array entry and put it to standard output:
 
<syntaxhighlight lang=Tcl>
puts $phonebook(Sally\ Smart)
</syntaxhighlight>
 
Which returns this result:
 
<syntaxhighlight lang=Text>
555-9999
</syntaxhighlight>
</source>
 
To retrieve the entire array as a dictionary:
=== Visual Basic ===
 
<syntaxhighlight lang=Tcl>
There is no standard implementation common to all dialects. [[Visual Basic]] can use the Dictionary class from the [[Windows Scripting Host|Microsoft Scripting Runtime]] (which is shipped with Visual Basic 6):
array get phonebook
</syntaxhighlight>
 
The result can be (order of keys is unspecified, not because the dictionary is unordered, but because the array is):
<source lang="vb">
 
<syntaxhighlight lang=Tcl>
{Sally Smart} 555-9999 {J. Random Hacker} 553-1337 {John Doe} 555-1212
</syntaxhighlight>
 
====dict====
<syntaxhighlight lang=Tcl>
set phonebook [dict create {Sally Smart} 555-9999 {John Doe} 555-1212 {J. Random Hacker} 553-1337]
</syntaxhighlight>
 
To look up an item:
 
<syntaxhighlight lang=Tcl>
dict get $phonebook {John Doe}
</syntaxhighlight>
 
To iterate through a dict:
 
<syntaxhighlight lang=Tcl>
foreach {name number} $phonebook {
puts "name: $name\nnumber: $number"
}
</syntaxhighlight>
 
=== Visual Basic ===
[[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="vbnet">
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
Line 898 ⟶ 1,943:
MsgBox name & " = " & phoneBook(name)
Next
</syntaxhighlight>
</source>
 
===Visual Basic .NET===
[[Visual Basic .NET]] relies onuses the collection classes provided by the [[.NET Framework]]:.
 
====Creation====
<source lang="vb">
The following code demonstrates the creation and population of a dictionary (see [[#C#|the C# example on this page]] for additional information):
Dim phoneBook As New System.Collections.Generic.Dictionary(Of String, String)
phoneBook("Sally Smart") = "555-9999"
phoneBook("John Doe") = "555-1212"
phoneBook("J. Random Hacker") = "553-1337"
For Each entry As KeyValuePair(Of String, String) In phoneBook
MsgBox(entry.Key & " = " & entry.Value)
Next
</source>
 
<syntaxhighlight lang=VBNet>
=== Windows PowerShell ===
Dim dic As New System.Collections.Generic.Dictionary(Of String, String)
dic.Add("Sally Smart", "555-9999")
dic("John Doe") = "555-1212"
dic.Item("J. Random Hacker") = "553-1337"
</syntaxhighlight>
 
An alternate syntax would be to use a ''collection initializer'', which compiles down to individual calls to <code>Add</code>:
Unlike many other [[command line interpreter]]s, [[Windows PowerShell|PowerShell]] has built-in, language-level support for defining associative arrays.
 
<syntaxhighlight lang=VBNet>
For example:
Dim dic As New System.Collections.Dictionary(Of String, String) From {
{"Sally Smart", "555-9999"},
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}
}
</syntaxhighlight>
 
====Access by key====
<source lang="text">
Example demonstrating access (see [[#C# access|C# access]]):
 
<syntaxhighlight lang=VBNet>
Dim sallyNumber = dic("Sally Smart")
' or
Dim sallyNumber = dic.Item("Sally Smart")
</syntaxhighlight>
<syntaxhighlight lang=VBNet>
Dim result As String = Nothing
Dim sallyNumber = If(dic.TryGetValue("Sally Smart", result), result, "n/a")
</syntaxhighlight>
 
====Enumeration====
Example demonstrating enumeration (see [[#C# enumeration]]):
 
<syntaxhighlight lang=VBNet>
' loop through the collection and display each entry.
For Each kvp As KeyValuePair(Of String, String) In dic
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value)
Next
</syntaxhighlight>
 
=== Windows PowerShell ===
Unlike many other [[command line interpreter]]s, [[Windows PowerShell]] has built-in, language-level support for defining associative arrays:
 
<syntaxhighlight lang=PowerShell>
$phonebook = @{
'Sally Smart' = '555-9999';
Line 924 ⟶ 2,000:
'J. Random Hacker' = '553-1337'
}
</syntaxhighlight>
</source>
 
LikeAs in JavaScript, if the property name is a valid identifier, the quotes can be omitted, e.g.:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$myOtherObject = @{ foo = 42; bar = $false }
</syntaxhighlight>
</source>
 
Entries can be separated by either a semicolon or a newline, e.g.:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$myOtherObject = @{ foo = 42
bar = $false ;
zaz = 3
}
</syntaxhighlight>
</source>
 
Keys and values can be any [[.NET Framework|.NET]] object type, e.g.:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$now = [DateTime]::Now
$tomorrow = $now.AddDays(1)
Line 950 ⟶ 2,026:
(Get-Process calc) = $tomorrow
}
</syntaxhighlight>
</source>
 
It is also possible to create an empty associative array and add single entries, or even other associative arrays, to it later on.:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$phonebook = @{}
$phonebook += @{ 'Sally Smart' = '555-9999' }
$phonebook += @{ 'John Doe' = '555-1212'; 'J. Random Hacker' = '553-1337' }
</syntaxhighlight>
</source>
 
New entries can also be added by using the array index operator, the property operator, or the <code>Add()</code> method of the underlying .NET object:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$phonebook = @{}
$phonebook['Sally Smart'] = '555-9999'
$phonebook.'John Doe' = '555-1212'
$phonebook.Add('J. Random Hacker', '553-1337')
</syntaxhighlight>
</source>
 
To dereference assigned objects, the array index operator, the property operator, or the parameterized property <code>Item()</code> of the .NET object can be used:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$phonebook['Sally Smart']
$phonebook.'John Doe'
$phonebook.Item('J. Random Hacker')
</syntaxhighlight>
</source>
 
You can loop through an associative array as follows:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$phonebook.Keys | foreach { "Number for {0}: {1}" -f $_,$phonebook.$_ }
</syntaxhighlight>
</source>
 
An entry can be removed using the <code>Remove()</code> method of the underlying .NET object:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$phonebook.Remove('Sally Smart')
</syntaxhighlight>
</source>
 
Hash tables can be added, e.g.:
 
<sourcesyntaxhighlight lang="text"PowerShell>
$hash1 = @{ a=1; b=2 }
$hash2 = @{ c=3; d=4 }
$hash3 = $hash1 + $hash2
</syntaxhighlight>
</source>
 
==Data serialization formats support==
{{Expand section|date=September 2010}}
 
Many data serialization formats also support associative arrays (see [[Comparison of data serialization formats#Syntax comparison of human-readable formats|this table]])
 
===JSON===
In [[JSON]], associative arrays are also referred to as objects. Keys can only be strings.
 
<syntaxhighlight lang=JavaScript>
{
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"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>
 
===YAML===
[[YAML]] associative arrays are also called map elements or key-value pairs. YAML places no restrictions on the types of keys; in particular, they are not restricted to being scalar or string values.
 
<syntaxhighlight lang=YAML>
Sally Smart: 555-9999
John Doe: 555-1212
J. Random Hacker: 555-1337
</syntaxhighlight>
 
== References ==
{{Reflist|2}}
<references/>
 
[[Category:Associative arrays|Programming language comparison]]
[[Category:Programming language comparisons|*Mapping]]
[[Category:Articles with example Julia code]]