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

Content deleted Content added
m F#: {{code}}
m F#: {{code}}
 
(24 intermediate revisions by 16 users not shown)
Line 2:
{{TOC limit|3}}
 
This '''Comparisoncomparison of programming languages (associative arrays)''' compares the features of [[associative array]] [[data structure]]s or array-lookup processing for over 40 computer [[programming language]]s.
 
==Language support==
Line 8:
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
 
===AwkAWK===
[[AwkAWK]] has built-in, language-level support for associative arrays.
 
For example:
 
<syntaxhighlight lang="awk">
phonebook["Sally Smart"] = "555-9999"
phonebook["John Doe"] = "555-1212"
Line 29:
The user can search for elements in an associative array, and delete elements from the array.
 
The following shows how multi-dimensional associative arrays can be simulated in standard AwkAWK using concatenation and the built-in string-separator variable SUBSEP:
 
<syntaxhighlight lang=awk>
Line 47:
There is no standard implementation of associative arrays in [[C (programming language)|C]], but a 3rd-party library, C Hash Table, with BSD license, is available.<ref>[https://web.archive.org/web/20071015024120/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], archived [https://web.archive.org/web/20040902160534/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], with the source code available [https://github.com/davidar/c-hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code></ref>
 
Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key.<ref>{{cite web |title=uthash: a hash table for C structures |url=httphttps://uthash.sourceforge.net/ |website=Github |access-date=3 August 2020}}</ref>
 
Finally, the [[GLib]] library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.<ref>{{cite web |title=Hash Tables |url=https://developer.gnome.org/glib/stable/glib-Hash-Tables.html |website=Gnome Developer |access-date=3 August 2020}}</ref>
Line 63:
* assigning to the backing property of the indexer, for which the indexer is [[syntactic sugar]] (not applicable to C#, see [[#F#|F#]] or [[#Visual Basic .NET|VB.NET]] examples).
 
<syntaxhighlight lang=CSharp"csharp">
Dictionary<string,var string> dicdictionary = new Dictionary<string, string>();
dicdictionary.Add("Sally Smart", "555-9999");
dicdictionary["John Doe"] = "555-1212";
// Not allowed in C#.
// dicdictionary.Item("J. Random Hacker") = "553-1337";
dicdictionary["J. Random Hacker"] = "553-1337";
</syntaxhighlight>
 
The dictionary can also be initialized during construction using a "collection initializer", which compiles to repeated calls to <code>Add</code>.
 
<syntaxhighlight lang=CSharp"csharp">
var dicdictionary = new Dictionary<string, string> {
{ "Sally Smart", "555-9999" },
{ "John Doe", "555-1212" },
Line 85:
Values are primarily retrieved using the indexer (which throws an exception if the key does not exist) and the <code>TryGetValue</code> method, which has an output parameter for the sought value and a Boolean return-value indicating whether the key was found.
 
<syntaxhighlight lang=CSharp"csharp">
var sallyNumber = dicdictionary["Sally Smart"];
</syntaxhighlight>
<syntaxhighlight lang=CSharp"csharp">
var sallyNumber = (dicdictionary.TryGetValue("Sally Smart", out var result) ? result : "n/a";
</syntaxhighlight>
In this example, the <code>sallyNumber</code> value will now contain the string <code>"555-9999"</code>.
Line 97:
 
The following demonstrates enumeration using a [[foreach loop]]:
<syntaxhighlight lang=CSharp"csharp">
// loop through the collection and display each entry.
foreach (KeyValuePair<string,string> kvp in dicdictionary)
{
Console.WriteLine("Phone number for {0} is {1}", kvp.Key, kvp.Value);
Line 108:
[[C++]] has a form of associative array called [[map (C++)|<code>std::map</code>]] (see [[Standard Template Library#Containers]]). One could create a phone-book map with the following code in C++:
 
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 122:
 
Or less efficiently, as this creates temporary <code>std::string</code> values:
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 136:
With the extension of [[C++11#Initializer lists|initialization lists]] in C++11, entries can be added during a map's construction as shown below:
 
<syntaxhighlight lang=Cpp"cpp">
#include <map>
#include <string>
Line 151:
You can iterate through the list with the following code (C++03):
 
<syntaxhighlight lang=Cpp"cpp">
std::map<std::string, std::string>::iterator curr, end;
for(curr = phone_book.begin(), end = phone_book.end(); curr != end; ++curr)
Line 159:
The same task in C++11:
 
<syntaxhighlight lang=Cpp"cpp">
for(const auto& curr : phone_book)
std::cout << curr.first << " = " << curr.second << std::endl;
Line 166:
Using the structured binding available in [[C++17]]:
 
<syntaxhighlight lang=Cpp"cpp">
for (const auto& [name, number] : phone_book) {
std::cout << name << " = " << number << std::endl;
Line 174:
In C++, the <code>std::map</code> class is [[Generic programming#Templates in C.2B.2B|templated]] which allows the [[data type]]s of keys and values to be different for different <code>map</code> instances. For a given instance of the <code>map</code> class the keys must be of the same base type. The same must be true for all of the values. Although <code>std::map</code> is typically implemented using a [[self-balancing binary search tree]], C++11 defines a second map called <code>[[std::unordered_map]]</code>, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the [[Standard Template Library]] (STL) as well, usually called <code>hash_map</code>, available from such implementations as SGI and STLPort.
 
===CFMLCobra===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
A structure in [[CFML]] is equivalent to an associative array:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
 
===ColdFusion Markup Language===
A structure in [[CFMLColdFusion Markup Language]] (CFML) is equivalent to an associative array:
 
<syntaxhighlight lang=CFS>
Line 188 ⟶ 212:
writeDump(phoneBook); // entire struct
</syntaxhighlight>
 
===Cobra===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
{{sxhl|2=python|1=<nowiki/>
dic as Dictionary<of String, String> = Dictionary<of String, String>()
dic.add('Sally Smart', '555-9999')
dic.add('John Doe', '555-1212')
dic.add('J. Random Hacker', '553-1337')
assert dic['Sally Smart'] == '555-9999'
}}
Alternatively, a dictionary can be initialized with all items during construction:
{{sxhl|2=python|1=<nowiki/>
dic = {
'Sally Smart':'555-9999',
'John Doe':'555-1212',
'J. Random Hacker':'553-1337'
}
}}
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
{{sxhl|2=python|1=<nowiki/>
for key, val in dic
print "[key]'s phone number is [val]"
}}
 
===D===
[[D programming language|D]] offers direct support for associative arrays in the core language; such arrays are implemented as a chaining hash table with binary trees.<ref>{{Cite web|title=Associative Arrays - D Programming Language|url=https://dlang.org/spec/hash-map.html|access-date=2021-05-07|website=dlang.org}}</ref> The equivalent example would be:
 
<syntaxhighlight lang=D"d">
int main() {
string[ string ] phone_book;
Line 230:
Looping through all properties and associated values, and printing them, can be coded as follows:
 
<syntaxhighlight lang=D"d">
foreach (key, value; phone_book) {
writeln("Number for " ~ key ~ ": " ~ value );
Line 238:
A property can be removed as follows:
 
<syntaxhighlight lang=D"d">
phone_book.remove("Sally Smart");
</syntaxhighlight>
 
===Delphi===
[[Delphi (programming languagesoftware)|Delphi]] supports several standard containers, including TDictionary<T>:
 
<syntaxhighlight lang=Delphi"delphi">
uses
SysUtils,
Line 265:
</syntaxhighlight>
 
Versions ofPre-2009 Delphi prior to 2009versions do not offer direct support for associative arrays directly. However, associativeSuch arrays can be simulated using the TStrings class:
 
<syntaxhighlight lang=Delphi"delphi">
procedure TForm1.Button1Click(Sender: TObject);
var
Line 298:
Keylists are lists of [[tuple]]s, where the first element of each tuple is a key, and the second is a value. Functions for operating on keylists are provided in the <code>lists</code> module.
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook = [{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
Line 306:
Accessing an element of the keylist can be done with the <code>lists:keyfind/3</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
{_, Phone} = lists:keyfind("Sally Smith", 1, PhoneBook),
io:format("Phone number: ~s~n", [Phone]).
Line 314:
Dictionaries are implemented in the <code>dict</code> module of the standard library. A new dictionary is created using the <code>dict:new/0</code> function and new key/value pairs are stored using the <code>dict:store/3</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook1 = dict:new(),
PhoneBook2 = dict:store("Sally Smith", "555-9999", Dict1),
Line 323:
Such a serial initialization would be more idiomatically represented in Erlang with the appropriate function:
 
<syntaxhighlight lang=Erlang"erlang">
PhoneBook = dict:from_list([{"Sally Smith", "555-9999"},
{"John Doe", "555-1212"},
Line 331:
The dictionary can be accessed using the <code>dict:find/2</code> function:
 
<syntaxhighlight lang=Erlang"erlang">
{ok, Phone} = dict:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 341:
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"erlang">
PhoneBook = #{"Sally Smith" => "555-9999",
"John Doe" => "555-1212",
Line 349:
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"erlang">
{ok, Phone} = maps:find("Sally Smith", PhoneBook),
io:format("Phone: ~s~n", [Phone]).
Line 356:
Unlike dictionaries, maps can be pattern matched upon:
 
<syntaxhighlight lang=Erlang"erlang">
#{"Sally Smith", Phone} = PhoneBook,
io:format("Phone: ~s~n", [Phone]).
Line 363:
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"erlang">
PhoneBook2 = PhoneBook#{
% the `:=` operator updates the value associated with an existing key
Line 375:
===F#===
 
===={{code|Map<'Key,'Value>}}====
At runtime, [[F Sharp (programming language)|F#]] provides the <code>Collections.Map<'Key,'Value></code> type, which is an immutable [[AVL tree]].
 
Line 381:
The following example calls the <code>Map</code> constructor, which operates on a list (a semicolon delimited sequence of elements enclosed in square brackets) of tuples (which in F# are comma-delimited sequences of elements).
 
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 391:
 
=====Access by key=====
Values can be looked up via one of the <code>Map</code> members, such as its indexer or <code>Item</code> property (which throw an [[Exception handling|exception]] if the key does not exist) or the <code>TryFind</code> function, which returns an [[option type]] with a value of <{{code>|Some <result></code>|f#}}, for a successful lookup, or <code>None</code>, for an unsuccessful one. [[Pattern matching]] can then be used to extract the raw value from the result, or a default value can be set.
 
<syntaxhighlight lang="fsharp">
let sallyNumber = numbers.["Sally Smart"]
// or
Line 407:
In both examples above, the <code>sallyNumber</code> value would contain the string <code>"555-9999"</code>.
 
===={{code|Dictionary<'TKey,'TValue>}}====
Because F# is a .NET language, it also has access to features of the [[.NET Framework]], including the {{code|System.Collections.Generic.Dictionary<'TKey,'TValue>|f#}} type (which is implemented as a [[hash table]]), which is the primary associative array type used in C# and Visual Basic. This type may be preferred when writing code that is intended to operate with other languages on the .NET Framework, or when the performance characteristics of a hash table are preferred over those of an AVL tree.
 
=====Creation=====
The <code>dict</code> function provides a means of conveniently creating a .NET dictionary that is not intended to be mutated; it accepts a sequence of tuples and returns an immutable object that implements <{{code>|IDictionary<'TKey,'TValue></code>|f#}}.
 
<syntaxhighlight lang="fsharp">
let numbers =
[
Line 424:
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")
Line 434:
<code>IDictionary</code> instances have an indexer that is used in the same way as <code>Map</code>, although the equivalent to <code>TryFind</code> is <code>TryGetValue</code>, which has an output parameter for the sought value and a Boolean return value indicating whether the key was found.
 
<syntaxhighlight lang="fsharp">
let sallyNumber =
let mutable result = ""
Line 441:
 
F# also allows the function to be called as if it had no output parameter and instead returned a tuple containing its regular return value and the value assigned to the output parameter:
<syntaxhighlight lang="fsharp">
let sallyNumber =
match numbers.TryGetValue("Sally Smart") with
Line 459:
[[Visual FoxPro]] implements mapping with the Collection Class.
 
<syntaxhighlight lang="visualfoxprofoxpro">
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) – key must be character
Line 476:
Adding elements one at a time:
 
<syntaxhighlight lang=Go"go">
phone_book := make(map[string] string) // make an empty map
phone_book["Sally Smart"] = "555-9999"
Line 485:
A map literal:
 
<syntaxhighlight lang=Go"go">
phone_book := map[string] string {
"Sally Smart": "555-9999",
Line 495:
Iterating through a map:
 
<syntaxhighlight lang=Go"go">
// over both keys and values
for key, value := range phone_book {
Line 508:
 
===Haskell===
The [[Haskell (programming language)|Haskell]] programming language provides only one kind of associative container – a list of pairs:
 
<syntaxhighlight lang="Haskellhaskell">
m = [("Sally Smart", "555-9999"), ("John Doe", "555-1212"), ("J. Random Hacker", "553-1337")]
 
Line 520:
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just 'result{{' "}} when found.
 
The [[Glasgow Haskell Compiler|GHC]] (GHC), the most commonly used implementation of Haskell, provides two more types of associative containers. Other implementations mightmay also provide these.
 
One is polymorphic functional maps (represented as immutable balanced binary trees):
 
<syntaxhighlight lang="Haskellhaskell" highlight="1">
import qualified Data.Map as M
 
Line 553:
Just "555-1212"
 
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the [[Monad_Monad (functional_programmingfunctional programming)#IO_monadIO monad|IO monad]].
 
===Java===
In [[Java (programming language)|Java]] associative arrays are implemented as "maps", which are part of the [[Java collections framework]]. Since [[Java Platform, Standard Edition|J2SE]] 5.0 and the introduction of [[generic programming|generics]] into Java, collections can have a type specified; for example, an associative array that maps strings to strings might be specified as follows:
 
<syntaxhighlight lang=Java"java">
Map<String, String> phoneBook = new HashMap<String, String>();
phoneBook.put("Sally Smart", "555-9999");
Line 567:
The {{Javadoc:SE|java/util|Map|get(java.lang.Object)|name=get}} method is used to access a key; for example, the value of the expression <code>phoneBook.get("Sally Smart")</code> is <code>"555-9999"</code>. This code uses a hash map to store the associative array, by calling the constructor of the {{Javadoc:SE|java/util|HashMap}} class. However, since the code only uses methods common to the interface {{Javadoc:SE|java/util|Map}}, a self-balancing binary tree could be used by calling the constructor of the {{Javadoc:SE|java/util|TreeMap}} class (which implements the subinterface {{Javadoc:SE|java/util|SortedMap}}), without changing the definition of the <code>phoneBook</code> variable, or the rest of the code, or using other underlying data structures that implement the <code>Map</code> interface.
 
The hash function in Java, used by HashMap and HashSet, is provided by the {{Javadoc:SE|java/lang|Object|hashCode()}} method. Since every class in Java [[Inheritance (computerobject-oriented scienceprogramming)|inherits]] from {{Javadoc:SE|java/lang|Object}}, every object has a hash function. A class can [[Method overriding (programming)|override]] the default implementation of <code>hashCode()</code> to provide a custom hash function more in accordance with the properties of the object.
 
The <code>Object</code> class also contains the {{Javadoc:SE|name=equals(Object)|java/lang|Object|equals(java.lang.Object)}} method, which tests an object for equality with another object. Hashed data structures in Java rely on objects maintaining the following contract between their <code>hashCode()</code> and <code>equals()</code> methods:
Line 573:
For two objects ''a'' and ''b'',
 
<syntaxhighlight lang=Java"java">
a.equals(b) == b.equals(a)
if a.equals(b), then a.hashCode() == b.hashCode()
Line 594:
A map can be initialized with all items during construction:
 
<syntaxhighlight lang=JavaScript"javascript">
const phoneBook = new Map([
["Sally Smart", "555-9999"],
Line 604:
Alternatively, you can initialize an empty map and then add items:
 
<syntaxhighlight lang=JavaScript"javascript">
const phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
Line 614:
Accessing an element of the map can be done with the <code>get</code> method:
 
<syntaxhighlight lang=JavaScript"javascript">
const sallyNumber = phoneBook.get("Sally Smart");
</syntaxhighlight>
Line 623:
The keys in a map are ordered. Thus, when iterating through it, a map object returns keys in order of insertion. The following demonstrates enumeration using a for-loop:
 
<syntaxhighlight lang=JavaScript"javascript">
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
Line 632:
A key can be removed as follows:
 
<syntaxhighlight lang=JavaScript"javascript">
phoneBook.delete("Sally Smart");
</syntaxhighlight>
Line 643:
An object literal is written as <code>{ property1: value1, property2: value2, ... }</code>. For example:
 
<syntaxhighlight lang=JavaScript"javascript">
const myObject = {
"Sally Smart": "555-9999",
Line 723:
Declare dictionary:
<syntaxhighlight lang="julia">
phonebook = Dict( "Sally Smart" => "555-9999", "John Doe" => "555-1212", "J. Random Hacker" => "555-1337" )
</syntaxhighlight>
 
Access element:
 
<syntaxhighlight lang="julia">
phonebook["Sally Smart"]
</syntaxhighlight>
 
Add element:
<syntaxhighlight lang="julia">
 
phonebook["New Contact"] = "555-2222"
</syntaxhighlight>
 
Delete element:
<syntaxhighlight lang="julia">
delete!(phonebook, "Sally Smart")
</syntaxhighlight>
 
Get keys and values as [[Iterator#Implicit_iteratorsImplicit iterators|iterables]]:
delete!(phonebook, "Sally Smart")
<syntaxhighlight lang="julia">
 
keys(phonebook)
Get keys and values as [[Iterator#Implicit_iterators|iterables]]:
values(phonebook)
 
</syntaxhighlight>
keys(phonebook)
values(phonebook)
 
===KornShell 93, and compliant shells===
Line 749 ⟶ 754:
Definition:
<syntaxhighlight lang="ksh">
typeset -A phonebook; # ksh93; in bash4+, "typeset" is a synonym of the more preferred "declare", which works identically in this case
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
declare -A phonebook; # bash4
phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
</syntaxhighlight>
 
Dereference:
<syntaxhighlight lang="ksh">
${phonebook["John Doe"]};
</syntaxhighlight>
 
Line 798 ⟶ 802:
</syntaxhighlight>
 
Searching for an entry by its key is performed via <code>assoc</code>, which might be configured for the test predicate and direction, especially searching the association list from its end to its front. The result, if positive, returns the entire entry cons, not only its value. Failure to obtain a matching key ledsleads to a return of the <code>NIL</code> value.
 
<syntaxhighlight lang=Lisp>
Line 1,070 ⟶ 1,074:
 
<syntaxhighlight lang="mathematica">
phonebook = <| "Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337" |>;
</syntaxhighlight>
 
Line 1,078 ⟶ 1,082:
 
<syntaxhighlight lang="mathematica">
phonebook[[Key["Sally Smart"]]]
</syntaxhighlight>
 
Line 1,084 ⟶ 1,088:
 
<syntaxhighlight lang="mathematica">
phonebook[["Sally Smart"]]
</syntaxhighlight>
 
Line 1,137 ⟶ 1,141:
</syntaxhighlight>
 
In Mac OS X 10.5+ and iPhone OS, dictionary keys can be enumerated more concisely using the <code>NSFastEnumeration</code> construct:<ref>{{cite web |title=NSFastEnumeration Protocol Reference |url=https://developer.apple.com/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |date=2011 |archive-url=https://web.archive.org/web/20160313082808/https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |archive-date=13 March 2016 |website=Mac Developer Library |access-date=3 August 2020}}</ref>
 
<syntaxhighlight lang=ObjC>
Line 1,221 ⟶ 1,225:
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
 
Line 1,230 ⟶ 1,234:
 
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
 
Line 1,237 ⟶ 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,248 ⟶ 1,252:
 
<syntaxhighlight lang=Java>
int[String][][double] a;
java.util.Map<String[Object], Integer> b;
</syntaxhighlight>
 
Line 1,265 ⟶ 1,269:
</syntaxhighlight>
 
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> – the key is surrounded by [[Bracket#Curly_bracketCurly bracket|curly braces]] and the hash name is prefixed by a <code>$</code>, indicating that the hash element itself is a scalar value, even though it is part of a hash. The value of <code>$phone_book{'John Doe'}</code> is <code>'555-1212'</code>. The <code>%</code> sigil is only used when referring to the hash as a whole, such as when asking for <code>keys %phone_book</code>.
 
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash:
Line 1,371 ⟶ 1,375:
 
===PHP===
[[PHP]]'s built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores arrays as associative arrays.<ref>About the implementation of [http://se.php.net/manual/en/language.types.array.php Arrays] in PHP</ref> So, PHP can have non-consecutively numerically- indexed arrays. The keys have to be of integer (floating point numbers are truncated to integer) or string type, while values can be of arbitrary types, including other arrays and objects. The arrays are heterogeneous: a single array can have keys of different types. PHP's associative arrays can be used to represent trees, lists, stacks, queues, and other common data structures not built into PHP.
 
An associative array can be declared using the following syntax:
Line 1,542 ⟶ 1,546:
</syntaxhighlight>
 
ToDictionary accessitems ancan entrybe inaccessed Python simply useusing the array indexing operator:
<syntaxhighlight lang="python">
>>> phonebook["Sally Smart"]
Line 1,577 ⟶ 1,581:
</syntaxhighlight>
 
Python 2.7 and 3.x also support dictionary[https://peps.python.org/pep-0274/ dict comprehensions] (similar to [[list comprehension]]s), a compact syntax for generating a dictionary from any iterator:
 
<syntaxhighlight lang="python">
Line 1,733 ⟶ 1,737:
 
===S-Lang===
[[S-Lang (programming language)|S-Lang]] has an associative array type:
 
<syntaxhighlight lang="text">
Line 1,930 ⟶ 1,934:
[[Visual Basic]] can use the Dictionary class from the [[Windows Scripting Host|Microsoft Scripting Runtime]] (which is shipped with Visual Basic 6). There is no standard implementation common to all versions:
 
<syntaxhighlight lang=VB"vbnet">
' Requires a reference to SCRRUN.DLL in Project Properties
Dim phoneBook As New Dictionary
Line 2,083 ⟶ 2,087:
"J. Random Hacker": "555-1337"
}
</syntaxhighlight>
 
===Cobra 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>