Content deleted Content added
→C#: copy editing |
m →F#: {{code}} |
||
(123 intermediate revisions by 26 users not shown) | |||
Line 1:
{{ProgLangCompare}}
{{TOC limit|3}}
This '''
==Language support==
Line 10 ⟶ 8:
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
===
[[
For example:
<syntaxhighlight lang="awk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
Line 31 ⟶ 29:
The user can search for elements in an associative array, and delete elements from the array.
The following shows how multi-dimensional associative arrays can be simulated in standard
<syntaxhighlight lang=awk>
Line 49 ⟶ 47:
There is no standard implementation of associative arrays in [[C (programming language)|C]], but a 3rd-party library, C Hash Table, with BSD license, is available.<ref>[https://web.archive.org/web/20071015024120/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], archived [https://web.archive.org/web/20040902160534/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], with the source code available [https://github.com/davidar/c-hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code></ref>
Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key.<ref>
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>
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.
Line 65 ⟶ 63:
* assigning to the backing property of the indexer, for which the indexer is [[syntactic sugar]] (not applicable to C#, see [[#F#|F#]] or [[#Visual Basic .NET|VB.NET]] examples).
<syntaxhighlight lang=
// Not allowed in C#.
//
</syntaxhighlight>
The dictionary can also be initialized
<syntaxhighlight lang="csharp">
var dictionary = new Dictionary<string, string> {
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
Line 84 ⟶ 83:
===={{anchor|C# access}}Access by key====
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
<syntaxhighlight lang="csharp">
var sallyNumber = dictionary["Sally Smart"];
</syntaxhighlight>
<syntaxhighlight lang=
var sallyNumber = (
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
===={{anchor|C# enumeration}}Enumeration====
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,
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang=
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
Line 105:
</syntaxhighlight>
===
[[C++
<syntaxhighlight lang=
#include <map>
#include <string>
Line 121:
</syntaxhighlight>
Or less efficiently, as
<syntaxhighlight lang=
#include <map>
#include <string>
Line 136:
With the extension of [[C++11#Initializer lists|initialization lists]] in C++11, entries can be added during a map's construction as shown below:
<syntaxhighlight lang=
#include <map>
#include <string>
Line 151:
You can iterate through the list with the following code (C++03):
<syntaxhighlight lang=
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
Line 157:
</syntaxhighlight>
The same task in
<syntaxhighlight lang=
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Line 166:
Using the structured binding available in [[C++17]]:
<syntaxhighlight lang=
for (const auto& [name, number] : phone_book) {
std::cout << name << " = " << number << std::endl;
Line 172:
</syntaxhighlight>
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
===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
===ColdFusion Markup Language===
A structure in [[ColdFusion Markup Language]] (CFML) is equivalent to an associative array:
<syntaxhighlight lang=CFS>
Line 189 ⟶ 213:
</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:
<syntaxhighlight lang="d">
int main() {
string[ string ] phone_book;
Line 226:
</syntaxhighlight>
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.
<syntaxhighlight lang=
foreach (key, value; phone_book) {
writeln("Number for " ~ key ~ ": " ~ value );
Line 239 ⟶ 238:
A property can be removed as follows:
<syntaxhighlight lang=
phone_book.remove("Sally Smart");
</syntaxhighlight>
===
[[Delphi (software)|Delphi]] supports several standard
<syntaxhighlight lang="delphi">
uses
SysUtils,
Line 265:
</syntaxhighlight>
<syntaxhighlight lang=
procedure TForm1.Button1Click(Sender: TObject);
var
Line 292:
</syntaxhighlight>
===
[[Erlang (programming language)|Erlang]] offers many
====Keylists====
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=
PhoneBook = [{"Sally
{"John Doe", "555-1212"},
{"J. Random Hacker", "553-1337"}].
Line 305 ⟶ 306:
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
<syntaxhighlight lang=
{_, Phone} = lists:keyfind("Sally
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=
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
Line 321 ⟶ 323:
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
<syntaxhighlight lang=
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=
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 335 ⟶ 338:
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 =
[
Line 353 ⟶ 390:
</syntaxhighlight>
=====
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
Line 367 ⟶ 404:
| 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 =
[
Line 385 ⟶ 422:
</syntaxhighlight>
When a mutable dictionary is needed, the constructor of
<syntaxhighlight lang="fsharp">
let numbers = System.Collections.Generic.Dictionary<string, string>()
numbers.Add("Sally Smart", "555-9999")
Line 393 ⟶ 431:
</syntaxhighlight>
=====
<code>IDictionary</code> instances have an indexer that is used in the same way as <code>Map</code>, although the equivalent to <code>TryFind</code> is <code>TryGetValue</code>, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
<syntaxhighlight lang="fsharp">
let sallyNumber =
let mutable result = ""
Line 402 ⟶ 440:
</syntaxhighlight>
F#
<syntaxhighlight lang="fsharp">
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
Line 411 ⟶ 449:
====Enumeration====
A dictionary or map can be enumerated using <code>Seq.map</code>.
<syntaxhighlight lang=fsharp>
// loop through the collection and display each entry.
Line 418 ⟶ 456:
</syntaxhighlight>
===
[[Visual FoxPro]] implements mapping with the Collection Class.
<syntaxhighlight lang="
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
Line 431 ⟶ 469:
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"
Line 445 ⟶ 484:
A map literal:
<syntaxhighlight lang="go">
phone_book := map[string] string {
"Sally Smart": "555-9999",
Line 453 ⟶ 493:
</syntaxhighlight>
Iterating
<syntaxhighlight lang="go">
// over both keys and values
for key, value := range phone_book {
Line 466 ⟶ 507:
</syntaxhighlight>
===
The [[Haskell]] programming language
<syntaxhighlight lang="
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
Line 477 ⟶ 518:
Just "555-1212"
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just
The [[Glasgow Haskell Compiler
One is polymorphic functional maps (represented as immutable balanced binary trees):
<syntaxhighlight lang="
import qualified Data.Map as M
Line 512 ⟶ 553:
Just "555-1212"
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the [[Monad (functional programming)#IO monad|IO monad]].
===
In [[Java (programming language)|Java]] associative arrays are implemented as "maps"
<syntaxhighlight lang=
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
Line 524 ⟶ 565:
</syntaxhighlight>
The {{Javadoc:SE|java/util|Map|get(java.lang.Object)|name=get}} method is used to access a key; for example, the value of the expression <code>phoneBook.get("Sally Smart")</code> is <code>"555-9999"</code>. This code uses a hash map to store the associative array, by calling the constructor of the {{Javadoc:SE|java/util|HashMap}} class. However, since the code only uses methods common to the interface {{Javadoc:SE|java/util|Map}}, a self-balancing binary tree could be used by calling the constructor of the {{Javadoc:SE|java/util|TreeMap}} class (which implements the subinterface {{Javadoc:SE|java/util|SortedMap}}), without changing the definition of the <code>phoneBook</code> variable, or the rest of the code, or using other underlying data structures that implement the <code>Map</code> interface.
The hash function in Java, used by HashMap and HashSet, is provided by the {{Javadoc:SE|java/lang|Object|hashCode()}} method. Since every class in Java [[Inheritance (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.
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:
For two objects ''a'' and ''b'',
<syntaxhighlight lang="java">
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
A further contract that a hashed data
Analogously, TreeMap, and other sorted data structures,
===
[[JavaScript]] (and its standardized version
====Map and WeakMap====
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default; it only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
=====Creation=====
A map can be initialized with all items during construction:
<syntaxhighlight lang=
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
Line 566 ⟶ 604:
Alternatively, you can initialize an empty map and then add items:
<syntaxhighlight lang=
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
Line 573 ⟶ 611:
</syntaxhighlight>
=====
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
=====
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}`);
}
Line 596 ⟶ 632:
A key can be removed as follows:
<syntaxhighlight lang=
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",
};
</syntaxhighlight>
To prevent the lookup
<syntaxhighlight lang=JavaScript>
Object.setPrototypeOf(myObject, null);
</syntaxhighlight>
As of ECMAScript 5 (ES5),
<syntaxhighlight lang=JavaScript>
Object.assign(myObject, {
});
</syntaxhighlight>
Line 636 ⟶ 672:
<syntaxhighlight lang=JavaScript>
</syntaxhighlight>
Lookup is written using property
<syntaxhighlight lang=JavaScript>
Line 649 ⟶ 685:
<syntaxhighlight lang=JavaScript>
for (
}
</syntaxhighlight>
Line 658 ⟶ 694:
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
}
</syntaxhighlight>
Line 672 ⟶ 708:
<syntaxhighlight lang=JavaScript>
myObject[1]
myObject[[
myObject[{ toString
</syntaxhighlight>
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and <code>Map</code>/<code>WeakMap</code> classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine,
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.
===
In [[Julia (programming language)|Julia]], the following operations manage associative arrays.
Declare dictionary:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Access element:
<syntaxhighlight lang="julia">
phonebook["Sally Smart"]
</syntaxhighlight>
Add element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Delete element:
<syntaxhighlight lang="julia">
delete!(phonebook, "Sally Smart")
</syntaxhighlight>
Get keys and values as [[Iterator#Implicit iterators|iterables]]:
<syntaxhighlight lang="julia">
keys(phonebook)
values(phonebook)
</syntaxhighlight>
===KornShell 93, and compliant shells===
In [[Korn Shell|KornShell]] 93, and compliant shells (ksh93, bash4...), the following operations can be used with associative arrays.
<!-- Tested in ksh93 r -->
Definition:
<syntaxhighlight lang="ksh">
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
</syntaxhighlight>
Dereference:
<syntaxhighlight lang="ksh">
</syntaxhighlight>
===
[[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>
Line 727 ⟶ 772:
</syntaxhighlight>
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.
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.
Line 740 ⟶ 785:
</syntaxhighlight>
This function can
<syntaxhighlight lang=Lisp>
Line 757 ⟶ 802:
</syntaxhighlight>
Searching for an entry by its key is performed via <code>assoc</code>, which might be configured
<syntaxhighlight lang=Lisp>
Line 763 ⟶ 808:
</syntaxhighlight>
Two generalizations of <code>assoc</code> exist: <code>assoc-if</code> expects a predicate function
<syntaxhighlight lang=Lisp>
Line 803 ⟶ 848:
</syntaxhighlight>
All of the
<syntaxhighlight lang=Lisp>
Line 820 ⟶ 865:
</syntaxhighlight>
Iteration is accomplished
<syntaxhighlight lang=Lisp>
Line 836 ⟶ 881:
</syntaxhighlight>
<syntaxhighlight lang=Lisp>
Line 850 ⟶ 895:
</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
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
<syntaxhighlight lang=Lisp>
Line 861 ⟶ 906:
</syntaxhighlight>
The <code>gethash</code> function permits
<syntaxhighlight lang=Lisp>
Line 867 ⟶ 912:
</syntaxhighlight>
Additionally,
<syntaxhighlight lang=Lisp>
Line 873 ⟶ 918:
</syntaxhighlight>
An invocation of <code>gethash</code> actually returns two values: the value or substitute value for the key and a boolean indicator,
<syntaxhighlight lang=Lisp>
Line 888 ⟶ 933:
</syntaxhighlight>
<code>clrhash</code> completely empties the
<syntaxhighlight lang=Lisp>
Line 894 ⟶ 939:
</syntaxhighlight>
The dedicated <code>maphash</code> function
<syntaxhighlight lang=Lisp>
Line 903 ⟶ 948:
</syntaxhighlight>
Alternatively, the <code>loop</code> construct makes provisions for iterations,
<syntaxhighlight lang=Lisp>
Line 918 ⟶ 963:
</syntaxhighlight>
A further option
<syntaxhighlight lang=Lisp>
Line 929 ⟶ 974:
</syntaxhighlight>
It is easy to construct composite abstract data types in Lisp, using structures
===
[[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
<syntaxhighlight lang=C>
Line 943 ⟶ 988:
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
LPC drivers of the
<syntaxhighlight lang=C>
Line 957 ⟶ 1,002:
</syntaxhighlight>
LPC drivers modern enough to support a foreach() construct
===Lua===
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.
Line 981 ⟶ 1,027:
</syntaxhighlight>
If the key is a valid identifier (not a
Lookup is written using either square brackets, which always works, or dot notation, which only works for identifier keys:
Line 990 ⟶ 1,036:
</syntaxhighlight>
You can also loop through all keys and associated values with iterators or for
<syntaxhighlight lang=Lua>
Line 1,023 ⟶ 1,069:
</syntaxhighlight>
===
[[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">
</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">
</syntaxhighlight>
If the keys are strings, the Key keyword is not necessary, so:
<syntaxhighlight lang="mathematica">
</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]
===
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
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
WRITE "Phone Number :",^phonebook("Sally Smart"),!
Line 1,062 ⟶ 1,114:
FOR S NAME=$ORDER(^phonebook(NAME)) QUIT:NAME="" WRITE NAME," Phone Number :",^phonebook(NAME),!
===
[[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
<syntaxhighlight lang=ObjC>
Line 1,072 ⟶ 1,124:
</syntaxhighlight>
To access assigned objects, this command may be used:
<syntaxhighlight lang=ObjC>
Line 1,078 ⟶ 1,130:
</syntaxhighlight>
All keys or values can be
<syntaxhighlight lang=ObjC>
Line 1,089 ⟶ 1,141:
</syntaxhighlight>
<syntaxhighlight lang=ObjC>
Line 1,112 ⟶ 1,164:
</syntaxhighlight>
<syntaxhighlight lang=ObjC>
Line 1,118 ⟶ 1,170:
</syntaxhighlight>
===
The [[OCaml]] programming language provides three different associative containers. The simplest is a list of pairs:
<syntaxhighlight lang=OCaml>
Line 1,148 ⟶ 1,200:
</syntaxhighlight>
The code above uses OCaml's default hash function <code>Hashtbl.hash</code>, which is defined automatically for all types.
Finally, functional maps (represented as immutable balanced binary trees):
Line 1,163 ⟶ 1,215:
</syntaxhighlight>
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
Lists of pairs and functional maps both provide a purely functional interface.
===
{{More citations needed section|date=February 2011}}
The [[OptimJ]] programming language is an extension of Java 5. As
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
Line 1,182 ⟶ 1,234:
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
Line 1,189 ⟶ 1,241:
// iterate over the keys
for (String name : phoneBook.keys) {
System.out.println(name + " -> " + phoneBook[name]);
}
// phoneBook[name] access a value by a key (it looks like java array access)
Line 1,197 ⟶ 1,249:
</syntaxhighlight>
Of course, it is possible to define multi-dimensional arrays, to mix
<syntaxhighlight lang=Java>
</syntaxhighlight>
===
[[Perl 5]] has built-in, language-level support for associative arrays. Modern Perl
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>=></code> token, which is
<syntaxhighlight lang=Perl>
Line 1,217 ⟶ 1,269:
</syntaxhighlight>
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> – the key is surrounded by
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash:
Line 1,235 ⟶ 1,287:
</syntaxhighlight>
A hash
<syntaxhighlight lang=Perl>
Line 1,259 ⟶ 1,311:
</syntaxhighlight>
===Perl
[[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
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>=></code> token, which makes the key-value association clearer:
<syntaxhighlight lang=Perl6>
Line 1,272 ⟶ 1,324:
</syntaxhighlight>
Accessing a hash element uses the syntax <code>%hash_name{$key}</code> – the key is surrounded by
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash:
Line 1,282 ⟶ 1,334:
</syntaxhighlight>
By default, when iterating
<syntaxhighlight lang=Perl6>
Line 1,290 ⟶ 1,342:
</syntaxhighlight>
It
<syntaxhighlight lang=Perl6>
Line 1,298 ⟶ 1,350:
</syntaxhighlight>
<syntaxhighlight lang=Perl6>
Line 1,309 ⟶ 1,361:
</syntaxhighlight>
<syntaxhighlight lang=Perl6>
Line 1,322 ⟶ 1,374:
</syntaxhighlight>
===
[[PHP]]'s built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores
An associative array can be declared using the following syntax:
<syntaxhighlight lang=
$phonebook = array();
$phonebook['Sally Smart'] = '555-9999';
Line 1,358 ⟶ 1,410:
PHP can loop through an associative array as follows:
<syntaxhighlight lang=
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";
}
</syntaxhighlight>
PHP has an
===
[[Pike (programming language)|Pike]] has built-in support for
<syntaxhighlight lang=
mapping(string:string) phonebook = ([
"Sally Smart":"555-9999",
Line 1,386 ⟶ 1,438:
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
<syntaxhighlight lang="pike">
foreach(phonebook; string key; string value) {
write("%s:%s\n", key, value);
Line 1,396 ⟶ 1,448:
Or using an iterator object:
<syntaxhighlight lang="pike">
Mapping.Iterator i = get_iterator(phonebook);
while (i->index()) {
Line 1,404 ⟶ 1,456:
</syntaxhighlight>
Elements of a mapping can be removed using <code>m_delete</code>, which returns the value of the removed index:
<syntaxhighlight lang="pike">
string sallys_number = m_delete(phonebook, "Sally Smart");
</syntaxhighlight>
===
In [[PostScript]], associative arrays are called dictionaries. In Level 1 PostScript they must be created explicitly, but Level 2 introduced direct declaration using
<syntaxhighlight lang="postscript">
Line 1,430 ⟶ 1,482:
% Both methods leave the dictionary on the operand stack
</syntaxhighlight>
Dictionaries can be accessed directly, using <code>get</code>, or implicitly, by placing the dictionary on the dictionary stack using <code>begin</code>:
<syntaxhighlight lang="postscript">
Line 1,441 ⟶ 1,494:
</syntaxhighlight>
Dictionary contents can be iterated through using
<syntaxhighlight lang="postscript">
Line 1,451 ⟶ 1,504:
>> {exch =print ( is ) print ==} forall
</syntaxhighlight>
Which may output:
<syntaxhighlight lang="postscript">
That is 2
Line 1,458 ⟶ 1,513:
</syntaxhighlight>
Dictionaries can be augmented (up to their defined size only in Level 1) or altered using
<syntaxhighlight lang="postscript">
% define a dictionary for easy reuse:
Line 1,478 ⟶ 1,533:
=== Prolog ===
Some versions of [[Prolog]] include dictionary ("
===
In [[Python (programming language)|Python]], associative arrays are called
<syntaxhighlight lang=
phonebook = {
}
</syntaxhighlight>
<syntaxhighlight lang=
>>> phonebook[
'555-9999'
</syntaxhighlight>
Loop [[iterator#Python|iterating]] through all the keys of the dictionary:
<syntaxhighlight lang="python">
>>> for key in phonebook:
... print(key, phonebook[key])
Line 1,510 ⟶ 1,564:
Iterating through (key, value) tuples:
<syntaxhighlight lang=
>>> for key, value in phonebook.items():
... print(key, value)
Line 1,518 ⟶ 1,572:
</syntaxhighlight>
Dictionary keys can be individually deleted using the <code>del</code> statement. The corresponding value can be returned before the key-value pair
<syntaxhighlight lang=
>>> del phonebook[
>>> val = phonebook.pop(
>>> phonebook.keys() # Only one key left
['J. Random Hacker']
</syntaxhighlight>
Python 2.7 and 3.x also
<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. 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
<syntaxhighlight lang=
phonebook = {
14:
}
</syntaxhighlight>
Line 1,549 ⟶ 1,604:
The dictionary keys must be of an [[Immutable object|immutable]] data type. In Python, strings are immutable due to their method of implementation.
===
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
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"
Line 1,560 ⟶ 1,617:
"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>:
remove/key my-map "Sally Smart"
</syntaxhighlight>
===
In [[REXX]], associative arrays are called
<syntaxhighlight lang=
KEY = 'Sally Smart'
PHONEBOOK.KEY = '555-9999'
Line 1,616 ⟶ 1,661:
</syntaxhighlight>
Stem variables with numeric keys typically start at 1 and go up from there. The 0
<syntaxhighlight lang=
NAME.1 = 'Sally Smart'
NAME.2 = 'John Doe'
Line 1,626 ⟶ 1,671:
</syntaxhighlight>
REXX has no easy way of automatically accessing the keys
keys are stored in a separate associative array, with numeric keys.
===
In [[Ruby programming language|Ruby]] a hash table is used as follows:
<syntaxhighlight lang="rb">
phonebook = {
'Sally Smart' => '555-9999',
'John Doe' => '555-1212',
}
phonebook['John Doe']
</syntaxhighlight>
Ruby supports hash looping and iteration with the following syntax:
<syntaxhighlight lang="irb">
irb(main):007:0> ### iterate over keys and values
irb(main):008:0* phonebook.each {|key, value| puts key + " => " + value}
Line 1,669 ⟶ 1,711:
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.
===Rust===
The [[Rust (programming language)|Rust]] standard library provides a hash map (<code>std::collections::HashMap</code>) and a [[B-tree]] map (<code>std::collections::BTreeMap</code>). They share several methods with the same names, but have different requirements for the types of keys that can be inserted. The <code>HashMap</code> requires keys to implement the <code>Eq</code> ([[equivalence relation]]) and <code>Hash</code> (hashability) traits and it stores entries in an unspecified order, and the <code>BTreeMap</code> requires the <code>Ord</code> ([[total order]]) trait for its keys and it stores entries in an order defined by the key type. The order is reflected by the default iterators.
<syntaxhighlight lang="rust">
use std::collections::HashMap;
let mut phone_book = HashMap::new();
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.
<syntaxhighlight lang="rust">
for (name, number) in &phone_book {
println!("{} {}", name, number);
}
</syntaxhighlight>
There is also an iterator for keys:
<syntaxhighlight lang="rust">
for name in phone_book.keys() {
println!("{}", name);
}
</syntaxhighlight>
===S-Lang===
[[S-Lang]] has an associative array type:
<syntaxhighlight lang="text">
Line 1,681 ⟶ 1,746:
</syntaxhighlight>
You can also loop through an associated array in a number of ways
<syntaxhighlight lang="text">
Line 1,700 ⟶ 1,764:
</syntaxhighlight>
===
[[Scala (programming language)|Scala]] provides an immutable <code>Map</code> class as part of the <code>scala.collection</code> framework:
<syntaxhighlight lang=
val phonebook = Map("Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
Line 1,709 ⟶ 1,773:
</syntaxhighlight>
Scala's [[type inference]] will
<syntaxhighlight lang=
phonebook.get("Sally Smart")
</syntaxhighlight>
This returns an <code>Option</code> type, Scala's equivalent of
===
In [[Smalltalk]] a
<syntaxhighlight lang=
phonebook := Dictionary new.
phonebook at: 'Sally Smart' put: '555-9999'.
Line 1,727 ⟶ 1,791:
</syntaxhighlight>
To access an entry the message <code>#at:</code> is sent to the dictionary object
<syntaxhighlight lang=
phonebook at: 'Sally Smart'
</syntaxhighlight>
Which gives:
<syntaxhighlight lang=
'555-9999'
</syntaxhighlight>
A dictionary hashes, or compares, based on equality and marks both key and value as
[[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).
Because every object implements #hash, any object can be used as key (and of course also as value).
===
[[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">
Line 1,753 ⟶ 1,817:
</syntaxhighlight>
===
The SML'97 standard of the [[Standard ML]] programming language does not provide any associative containers. However, various implementations of Standard ML do provide associative containers.
The library of the popular [[Standard ML of New Jersey]] (SML/NJ) implementation provides a signature (somewhat like an "interface"), <code>ORD_MAP</code>, which defines a common interface for ordered functional (immutable) associative arrays. There are several general
<syntaxhighlight lang="sml">
Line 1,801 ⟶ 1,865:
</syntaxhighlight>
Monomorphic hash tables are also supported, using the <code>HashTableFn</code> functor.
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.
===
There are two [[Tcl]] facilities that support associative
====array====
<syntaxhighlight lang=Tcl>
set {phonebook(Sally Smart)} 555-9999
Line 1,837 ⟶ 1,880:
</syntaxhighlight>
If there is a
Alternatively, several array elements can be set
<syntaxhighlight lang=Tcl>
Line 1,845 ⟶ 1,888:
</syntaxhighlight>
To access one array entry and put it
<syntaxhighlight lang=Tcl>
Line 1,851 ⟶ 1,894:
</syntaxhighlight>
Which returns this result:
<syntaxhighlight lang=Text>
Line 1,869 ⟶ 1,912:
</syntaxhighlight>
===
<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=
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
Line 1,883 ⟶ 1,945:
</syntaxhighlight>
===
[[Visual Basic .NET]] uses the collection classes provided by the [[.NET Framework]].
====Creation====
The following code demonstrates the creation and population of a dictionary (see [[#C#|the C# example on this page]] for additional information):
<syntaxhighlight lang=VBNet>
Dim dic As New System.Collections.Generic.Dictionary(Of String, String)
Line 1,896 ⟶ 1,958:
</syntaxhighlight>
An
<syntaxhighlight lang=VBNet>
Dim dic As New System.Collections.Dictionary(Of String, String) From {
Line 1,906 ⟶ 1,969:
====Access by key====
Example demonstrating access (see [[#C# access|C# access]]):
<syntaxhighlight lang=VBNet>
Dim sallyNumber = dic("Sally Smart")
Line 1,919 ⟶ 1,982:
====Enumeration====
Example demonstrating enumeration (see [[#C# enumeration]]):
<syntaxhighlight lang=VBNet>
' loop through the collection and display each entry.
Line 1,928 ⟶ 1,991:
</syntaxhighlight>
===
Unlike many other [[command line interpreter]]s, [[Windows PowerShell]] has built-in, language-level support for defining associative arrays
<syntaxhighlight lang=PowerShell>
Line 1,941 ⟶ 2,002:
</syntaxhighlight>
<syntaxhighlight lang=PowerShell>
Line 1,947 ⟶ 2,008:
</syntaxhighlight>
Entries can be separated by either a semicolon or a newline
<syntaxhighlight lang=PowerShell>
Line 1,956 ⟶ 2,017:
</syntaxhighlight>
Keys and values can be any [[.NET Framework|.NET]] object type
<syntaxhighlight lang=PowerShell>
Line 1,967 ⟶ 2,028:
</syntaxhighlight>
It is also possible to create an empty associative array and add single entries, or even other associative arrays, to it later on
<syntaxhighlight lang=PowerShell>
Line 1,975 ⟶ 2,036:
</syntaxhighlight>
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:
<syntaxhighlight lang=PowerShell>
Line 1,984 ⟶ 2,045:
</syntaxhighlight>
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:
<syntaxhighlight lang=PowerShell>
Line 2,004 ⟶ 2,065:
</syntaxhighlight>
Hash tables can be added
<syntaxhighlight lang=PowerShell>
Line 2,017 ⟶ 2,078:
Many data serialization formats also support associative arrays (see [[Comparison of data serialization formats#Syntax comparison of human-readable formats|this table]])
===
In [[JSON]], associative arrays are also referred to as objects. Keys can only be strings.
<syntaxhighlight lang=JavaScript>
{
Line 2,027 ⟶ 2,089:
</syntaxhighlight>
===
[[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>
|