Associative array/Creation: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1: Line 1:
{{task|Basic language learning}}[[Category:Data Structures]]
[[Category:Data Structures]]
{{task|Basic language learning}}

;Task:
;Task:
The goal is to create an [[associative array]] (also known as a dictionary, map, or hash).
The goal is to create an [[associative array]] (also known as a dictionary, map, or hash).
Line 14: Line 14:


=={{header|11l}}==
=={{header|11l}}==
<syntaxhighlight lang=11l>V dict = [‘key1’ = 1, ‘key2’ = 2]
<syntaxhighlight lang="11l">V dict = [‘key1’ = 1, ‘key2’ = 2]
V value2 = dict[‘key2’]</syntaxhighlight>
V value2 = dict[‘key2’]</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
8th has 'maps' as built-in data types, and can use JSON to describe them:
8th has 'maps' as built-in data types, and can use JSON to describe them:
<syntaxhighlight lang=Forth>
<syntaxhighlight lang="forth">
{ "one" : 1, "two" : "bad" }
{ "one" : 1, "two" : "bad" }
</syntaxhighlight>
</syntaxhighlight>
Alternatively, they can be created in code:
Alternatively, they can be created in code:
<syntaxhighlight lang=Forth>
<syntaxhighlight lang="forth">
m:new "one" 1 m:! "two" "bad" m:!
m:new "one" 1 m:! "two" "bad" m:!
</syntaxhighlight>
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang=AArch64 Assembly>
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program hashmap64.s */
/* program hashmap64.s */
Line 429: Line 429:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
Because ActionScript does not have associative arrays in the normal sense, Object objects are used instead and keys are simply properties on those objects.
Because ActionScript does not have associative arrays in the normal sense, Object objects are used instead and keys are simply properties on those objects.
<syntaxhighlight lang=actionscript>var map:Object = {key1: "value1", key2: "value2"};
<syntaxhighlight lang="actionscript">var map:Object = {key1: "value1", key2: "value2"};
trace(map['key1']); // outputs "value1"
trace(map['key1']); // outputs "value1"


Line 442: Line 442:
=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
{{works with|GNAT|GPL 2007}}
<syntaxhighlight lang=ada>with Ada.Containers.Ordered_Maps;
<syntaxhighlight lang="ada">with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Text_IO;
Line 478: Line 478:
=={{header|Aikido}}==
=={{header|Aikido}}==
Aikido provides a native <em>map</em> for associative arrays. You can create them using a map literal and you can insert and remove items on the fly.
Aikido provides a native <em>map</em> for associative arrays. You can create them using a map literal and you can insert and remove items on the fly.
<syntaxhighlight lang=aikido>
<syntaxhighlight lang="aikido">
var names = {} // empty map
var names = {} // empty map
names["foo"] = "bar"
names["foo"] = "bar"
Line 502: Line 502:
=={{header|Aime}}==
=={{header|Aime}}==
Aime records are heterogenous associative arrays. No creation procedure is required, declaration is fine.
Aime records are heterogenous associative arrays. No creation procedure is required, declaration is fine.
<syntaxhighlight lang=aime>record r;</syntaxhighlight>
<syntaxhighlight lang="aime">record r;</syntaxhighlight>
<syntaxhighlight lang=aime>r_put(r, "A", 33); # an integer value
<syntaxhighlight lang="aime">r_put(r, "A", 33); # an integer value
r_put(r, "C", 2.5); # a real value
r_put(r, "C", 2.5); # a real value
r_put(r, "B", "associative"); # a string value</syntaxhighlight>
r_put(r, "B", "associative"); # a string value</syntaxhighlight>
Line 514: Line 514:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<syntaxhighlight lang=algol68>main:(
<syntaxhighlight lang="algol68">main:(


MODE COLOR = BITS;
MODE COLOR = BITS;
Line 600: Line 600:


Creating a new empty map of String to String:
Creating a new empty map of String to String:
<syntaxhighlight lang=apex>// Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap).
<syntaxhighlight lang="apex">// Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap).
Map<String, String> strMap = new Map<String, String>();
Map<String, String> strMap = new Map<String, String>();
strMap.put('a', 'aval');
strMap.put('a', 'aval');
Line 611: Line 611:


Creating a new map of String to String with values initialized:
Creating a new map of String to String with values initialized:
<syntaxhighlight lang=apex>Map<String, String> strMap = new Map<String, String>{
<syntaxhighlight lang="apex">Map<String, String> strMap = new Map<String, String>{
'a' => 'aval',
'a' => 'aval',
'b' => 'bval'
'b' => 'bval'
Line 621: Line 621:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<syntaxhighlight lang=apl>⍝ Create a namespace ("hash")
<syntaxhighlight lang="apl">⍝ Create a namespace ("hash")
X←⎕NS ⍬
X←⎕NS ⍬
Line 645: Line 645:


{{works with|GNU APL}}
{{works with|GNU APL}}
<syntaxhighlight lang=apl>
<syntaxhighlight lang="apl">
⍝ Assign some names
⍝ Assign some names
X.this←'that'
X.this←'that'
Line 681: Line 681:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang=ARM Assembly>
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI or android 32 bits */
/* ARM assembly Raspberry PI or android 32 bits */
/* program hashmap.s */
/* program hashmap.s */
Line 1,057: Line 1,057:
=={{header|Arturo}}==
=={{header|Arturo}}==


<syntaxhighlight lang=rebol>; create a dictionary
<syntaxhighlight lang="rebol">; create a dictionary
d: #[
d: #[
name: "john"
name: "john"
Line 1,078: Line 1,078:
=== Persistent association lists ===
=== Persistent association lists ===
The following implementation includes set, get, and delete, and also "generators", which are like iterators except they are closures rather than regular objects.
The following implementation includes set, get, and delete, and also "generators", which are like iterators except they are closures rather than regular objects.
<syntaxhighlight lang=ATS>(*------------------------------------------------------------------*)
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)


#define ATS_DYNLOADFLAG 0
#define ATS_DYNLOADFLAG 0
Line 1,324: Line 1,324:
Because the hash table is an AVL tree, performance will tend to be logarithmic. This assumes a good hash function, of course. With a bad hash function, performance may be linear.
Because the hash table is an AVL tree, performance will tend to be logarithmic. This assumes a good hash function, of course. With a bad hash function, performance may be linear.


<syntaxhighlight lang=ATS>(*------------------------------------------------------------------*)
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)


#define ATS_DYNLOADFLAG 0
#define ATS_DYNLOADFLAG 0
Line 1,917: Line 1,917:
=== True arrays ===
=== True arrays ===
[[AutoHotkey_L]] has [http://ahkscript.org/docs/Objects.htm Objects] which function as associative arrays.
[[AutoHotkey_L]] has [http://ahkscript.org/docs/Objects.htm Objects] which function as associative arrays.
<syntaxhighlight lang=AutoHotkey>associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23}
<syntaxhighlight lang="autohotkey">associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23}
MsgBox % associative_array.key1
MsgBox % associative_array.key1
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</syntaxhighlight>
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</syntaxhighlight>
Line 1,923: Line 1,923:
[[AutoHotkey_Basic]] does not have typical arrays.
[[AutoHotkey_Basic]] does not have typical arrays.
However, variable names can be concatenated, simulating associative arrays.
However, variable names can be concatenated, simulating associative arrays.
<syntaxhighlight lang=AutoHotkey>arrayX1 = first
<syntaxhighlight lang="autohotkey">arrayX1 = first
arrayX2 = second
arrayX2 = second
arrayX3 = foo
arrayX3 = foo
Line 1,932: Line 1,932:
=={{header|AutoIt}}==
=={{header|AutoIt}}==
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.
<syntaxhighlight lang=AutoIt>; Associative arrays in AutoIt.
<syntaxhighlight lang="autoit">; Associative arrays in AutoIt.
; All the required functions are below the examples.
; All the required functions are below the examples.


Line 2,063: Line 2,063:
=={{header|AWK}}==
=={{header|AWK}}==
Arrays in AWK are indeed associative arrays.
Arrays in AWK are indeed associative arrays.
<syntaxhighlight lang=awk>BEGIN {
<syntaxhighlight lang="awk">BEGIN {
a["red"] = 0xff0000
a["red"] = 0xff0000
a["green"] = 0x00ff00
a["green"] = 0x00ff00
Line 2,082: Line 2,082:
=={{header|Babel}}==
=={{header|Babel}}==


<syntaxhighlight lang=babel>
<syntaxhighlight lang="babel">
(("foo" 13)
(("foo" 13)
("bar" 42)
("bar" 42)
Line 2,088: Line 2,088:


=={{header|BaCon}}==
=={{header|BaCon}}==
<syntaxhighlight lang=qbasic>DECLARE associative ASSOC STRING
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING


associative("abc") = "first three"
associative("abc") = "first three"
Line 2,103: Line 2,103:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256>global values$, keys$
<syntaxhighlight lang="basic256">global values$, keys$
dim values$[1]
dim values$[1]
dim keys$[1]
dim keys$[1]
Line 2,222: Line 2,222:
This is cheating, I'm sure of it.
This is cheating, I'm sure of it.


<syntaxhighlight lang=dos>::assocarrays.cmd
<syntaxhighlight lang="dos">::assocarrays.cmd
@echo off
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEDELAYEDEXPANSION
Line 2,259: Line 2,259:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<syntaxhighlight lang=bbcbasic> REM Store some values with their keys:
<syntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
PROCputdict(mydict$, "00FF00", "green")
Line 2,283: Line 2,283:
=={{header|Bracmat}}==
=={{header|Bracmat}}==
The hash is the only built-in Bracmat class. It is best used for e.g. a large dictionary, when manipulation of a very long list of key/value pairs with pattern matching would become too CPU-intensive. The same key can be stored with different values, as the example shows. If that is not desirable, the key (and its value) should be removed first.
The hash is the only built-in Bracmat class. It is best used for e.g. a large dictionary, when manipulation of a very long list of key/value pairs with pattern matching would become too CPU-intensive. The same key can be stored with different values, as the example shows. If that is not desirable, the key (and its value) should be removed first.
<syntaxhighlight lang=bracmat> new$hash:?myhash
<syntaxhighlight lang="bracmat"> new$hash:?myhash
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
& (myhash..insert)$(formula.a+b+x^7)
Line 2,298: Line 2,298:


=={{header|Brat}}==
=={{header|Brat}}==
<syntaxhighlight lang=brat>h = [:] #Empty hash
<syntaxhighlight lang="brat">h = [:] #Empty hash


h[:a] = 1 #Assign value
h[:a] = 1 #Assign value
Line 2,312: Line 2,312:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
'''Platform:''' [[.NET]] 1.x
'''Platform:''' [[.NET]] 1.x
<syntaxhighlight lang=csharp>System.Collections.HashTable map = new System.Collections.HashTable();
<syntaxhighlight lang="csharp">System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";</syntaxhighlight>
map["key1"] = "foo";</syntaxhighlight>


'''Platform:''' [[.NET]] 2.0
'''Platform:''' [[.NET]] 2.0
<syntaxhighlight lang=csharp>Dictionary<string, string> map = new Dictionary<string,string>();
<syntaxhighlight lang="csharp">Dictionary<string, string> map = new Dictionary<string,string>();
map[ "key1" ] = "foo";</syntaxhighlight>
map[ "key1" ] = "foo";</syntaxhighlight>


{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
<syntaxhighlight lang=csharp>var map = new Dictionary<string, string> {{"key1", "foo"}};</syntaxhighlight>
<syntaxhighlight lang="csharp">var map = new Dictionary<string, string> {{"key1", "foo"}};</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
The C++ standard defines std::map as a means of creating an association between a key of one arbitrary type and a value of another arbitrary type. This requires the inclusion of the standard header '''map'''.
The C++ standard defines std::map as a means of creating an association between a key of one arbitrary type and a value of another arbitrary type. This requires the inclusion of the standard header '''map'''.


<syntaxhighlight lang=cpp>#include <map></syntaxhighlight>
<syntaxhighlight lang="cpp">#include <map></syntaxhighlight>


===Creation===
===Creation===
To create a simple map whose key is of type A and whose value is of type B, one would define the variable like so:
To create a simple map whose key is of type A and whose value is of type B, one would define the variable like so:
<syntaxhighlight lang=cpp>std::map<A, B> exampleMap</syntaxhighlight>
<syntaxhighlight lang="cpp">std::map<A, B> exampleMap</syntaxhighlight>


If one wanted to us a key type of '''int''' and a value of '''double''', you would define it like so:
If one wanted to us a key type of '''int''' and a value of '''double''', you would define it like so:


<syntaxhighlight lang=cpp>std::map<int, double> exampleMap</syntaxhighlight>
<syntaxhighlight lang="cpp">std::map<int, double> exampleMap</syntaxhighlight>


===Insertion===
===Insertion===
Line 2,339: Line 2,339:
====Operator[]====
====Operator[]====
The first method is using the [] operator.
The first method is using the [] operator.
<syntaxhighlight lang=cpp>exampleMap[7] = 3.14</syntaxhighlight>
<syntaxhighlight lang="cpp">exampleMap[7] = 3.14</syntaxhighlight>


Of course, you can use a variable (or any [[rvalue]] of the correct type) for the key or value parameters:
Of course, you can use a variable (or any [[rvalue]] of the correct type) for the key or value parameters:
<syntaxhighlight lang=cpp>int myKey = 7;
<syntaxhighlight lang="cpp">int myKey = 7;
double myValue = 3.14;
double myValue = 3.14;
exampleMap[myKey] = myValue;</syntaxhighlight>
exampleMap[myKey] = myValue;</syntaxhighlight>
====insert()====
====insert()====
The second approach is a little more complicated. We have to use the '''pair<>''' template:
The second approach is a little more complicated. We have to use the '''pair<>''' template:
<syntaxhighlight lang=cpp>exampleMap.insert(std::pair<int, double>(7,3.14));</syntaxhighlight>
<syntaxhighlight lang="cpp">exampleMap.insert(std::pair<int, double>(7,3.14));</syntaxhighlight>
or by using '''make_pair''' to avoid repeating key/value types:
or by using '''make_pair''' to avoid repeating key/value types:
<syntaxhighlight lang=cpp>exampleMap.insert(std::make_pair(7,3.14));</syntaxhighlight>
<syntaxhighlight lang="cpp">exampleMap.insert(std::make_pair(7,3.14));</syntaxhighlight>


===Lookup===
===Lookup===
Line 2,355: Line 2,355:
====operator[]====
====operator[]====
We use it as an rvalue, supplying the correct key:
We use it as an rvalue, supplying the correct key:
<syntaxhighlight lang=cpp>myValue = exampleMap[myKey]</syntaxhighlight>
<syntaxhighlight lang="cpp">myValue = exampleMap[myKey]</syntaxhighlight>
If the value doesn't already exist, a default-constructed object of the value's type will be inserted using the key you specified, and that default value will be returned.
If the value doesn't already exist, a default-constructed object of the value's type will be inserted using the key you specified, and that default value will be returned.


====find()====
====find()====
Alternatively, you can look up a value by using find(), storing its return value in an [[iterator]], and comparing the iterator against the map's end() [[sentinal value]]:
Alternatively, you can look up a value by using find(), storing its return value in an [[iterator]], and comparing the iterator against the map's end() [[sentinal value]]:
<syntaxhighlight lang=cpp>double myValue = 0.0;
<syntaxhighlight lang="cpp">double myValue = 0.0;
std::map<int, double>::iterator myIterator = exampleMap.find(myKey);
std::map<int, double>::iterator myIterator = exampleMap.find(myKey);
if(exampleMap.end() != myIterator)
if(exampleMap.end() != myIterator)
Line 2,374: Line 2,374:
===Example===
===Example===
This simple program creates a map, assigns a value to that map, retrieves a value from that map, and prints the value to STDOUT.
This simple program creates a map, assigns a value to that map, retrieves a value from that map, and prints the value to STDOUT.
<syntaxhighlight lang=cpp>#include <map>
<syntaxhighlight lang="cpp">#include <map>
#include <iostreams>
#include <iostreams>


Line 2,402: Line 2,402:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<syntaxhighlight lang=ceylon>import ceylon.collection {
<syntaxhighlight lang="ceylon">import ceylon.collection {


ArrayList,
ArrayList,
Line 2,444: Line 2,444:
The creation of the domain is independent from the creation of the array, and in fact the same domain can be used for multiple arrays, creating associative arrays with identical sets of keys. When the domain is changed, all arrays that use it will be reallocated.
The creation of the domain is independent from the creation of the array, and in fact the same domain can be used for multiple arrays, creating associative arrays with identical sets of keys. When the domain is changed, all arrays that use it will be reallocated.


<lang>// arr is an array of string to int. any type can be used in both places.
<syntaxhighlight lang="text">// arr is an array of string to int. any type can be used in both places.
var keys: domain(string);
var keys: domain(string);
var arr: [keys] int;
var arr: [keys] int;
Line 2,483: Line 2,483:


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang=lisp>{:key "value"
<syntaxhighlight lang="lisp">{:key "value"
:key2 "value2"
:key2 "value2"
:key3 "value3"}</syntaxhighlight>
:key3 "value3"}</syntaxhighlight>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<syntaxhighlight lang=cfm><cfset myHash = structNew()>
<syntaxhighlight lang="cfm"><cfset myHash = structNew()>
<cfset myHash.key1 = "foo">
<cfset myHash.key1 = "foo">
<cfset myHash["key2"] = "bar">
<cfset myHash["key2"] = "bar">
Line 2,496: Line 2,496:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<syntaxhighlight lang=lisp>;; default :test is #'eql, which is suitable for numbers only,
<syntaxhighlight lang="lisp">;; default :test is #'eql, which is suitable for numbers only,
;; or for implementation identity for other types!
;; or for implementation identity for other types!
;; Use #'equalp if you want case-insensitive keying on strings.
;; Use #'equalp if you want case-insensitive keying on strings.
Line 2,513: Line 2,513:
BlackBox Componente Builder<br/>
BlackBox Componente Builder<br/>
Using a handmade collections module with the following interface<br/>
Using a handmade collections module with the following interface<br/>
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
DEFINITION Collections;
DEFINITION Collections;


Line 2,583: Line 2,583:
</syntaxhighlight>
</syntaxhighlight>
The program:
The program:
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE BbtAssociativeArrays;
MODULE BbtAssociativeArrays;
IMPORT StdLog, Collections, Boxes;
IMPORT StdLog, Collections, Boxes;
Line 2,614: Line 2,614:


=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang=ruby>hash1 = {"foo" => "bar"}
<syntaxhighlight lang="ruby">hash1 = {"foo" => "bar"}


# hash literals that don't perfectly match the intended hash type must be given an explicit type specification
# hash literals that don't perfectly match the intended hash type must be given an explicit type specification
Line 2,621: Line 2,621:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>void main() {
<syntaxhighlight lang="d">void main() {
auto hash = ["foo":42, "bar":100];
auto hash = ["foo":42, "bar":100];
assert("foo" in hash);
assert("foo" in hash);
Line 2,627: Line 2,627:


=={{header|Dao}}==
=={{header|Dao}}==
<syntaxhighlight lang=dao>m = { => } # empty ordered map, future inserted keys will be ordered
<syntaxhighlight lang="dao">m = { => } # empty ordered map, future inserted keys will be ordered
h = { -> } # empty hash map, future inserted keys will not be ordered
h = { -> } # empty hash map, future inserted keys will not be ordered


Line 2,634: Line 2,634:


=={{header|Dart}}==
=={{header|Dart}}==
<syntaxhighlight lang=javascript>
<syntaxhighlight lang="javascript">
main() {
main() {
var rosettaCode = { // Type is inferred to be Map<String, String>
var rosettaCode = { // Type is inferred to be Map<String, String>
Line 2,687: Line 2,687:


=={{header|Delphi}}==
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi>program AssociativeArrayCreation;
<syntaxhighlight lang="delphi">program AssociativeArrayCreation;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 2,711: Line 2,711:


To create a dictionary associative array:
To create a dictionary associative array:
<syntaxhighlight lang=diego>use_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();


add_dict(tanzanianBanknoteObverseDipiction)_keys(500,1000,2000,5000,10000)_values(Karume,Nyerere,lion,black rhinoceros,elephant);
add_dict(tanzanianBanknoteObverseDipiction)_keys(500,1000,2000,5000,10000)_values(Karume,Nyerere,lion,black rhinoceros,elephant);
Line 2,718: Line 2,718:


To create a hash associative array:
To create a hash associative array:
<syntaxhighlight lang=diego>use_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();


add_hash(tanzanianBanknoteReverseDipiction)_values(
add_hash(tanzanianBanknoteReverseDipiction)_values(
Line 2,734: Line 2,734:
Dyalect has a <code>Tuple</code> data type which allows to add labels to values:
Dyalect has a <code>Tuple</code> data type which allows to add labels to values:


<syntaxhighlight lang=dyalect>var t = (x: 1, y: 2, z: 3)
<syntaxhighlight lang="dyalect">var t = (x: 1, y: 2, z: 3)
print(t.Keys().ToArray())</syntaxhighlight>
print(t.Keys().ToArray())</syntaxhighlight>


Line 2,742: Line 2,742:


=={{header|E}}==
=={{header|E}}==
<syntaxhighlight lang=e>[].asMap() # immutable, empty
<syntaxhighlight lang="e">[].asMap() # immutable, empty
["one" => 1, "two" => 2] # immutable, 2 mappings
["one" => 1, "two" => 2] # immutable, 2 mappings
[].asMap().diverge() # mutable, empty
[].asMap().diverge() # mutable, empty
Line 2,749: Line 2,749:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
(lib 'hash) ;; needs hash.lib
(lib 'hash) ;; needs hash.lib
(define H (make-hash)) ;; new hash table
(define H (make-hash)) ;; new hash table
Line 2,772: Line 2,772:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0:
ELENA 5.0:
<syntaxhighlight lang=elena>import system'collections;
<syntaxhighlight lang="elena">import system'collections;
public program()
public program()
Line 2,786: Line 2,786:


=== Strong typed dictionary ===
=== Strong typed dictionary ===
<syntaxhighlight lang=elena>import system'collections;
<syntaxhighlight lang="elena">import system'collections;


public program()
public program()
Line 2,801: Line 2,801:
=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<syntaxhighlight lang=elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def test_create do
def test_create do
IO.puts "< create Map.new >"
IO.puts "< create Map.new >"
Line 2,831: Line 2,831:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang=Lisp>(setq my-table (make-hash-table))
<syntaxhighlight lang="lisp">(setq my-table (make-hash-table))
(puthash 'key 'value my-table)</syntaxhighlight>
(puthash 'key 'value my-table)</syntaxhighlight>


<code>make-hash-table</code> compares keys with <code>eql</code> by default. This suits symbols and numbers (including floating point). For string keys an <code>equal</code> test can be used,
<code>make-hash-table</code> compares keys with <code>eql</code> by default. This suits symbols and numbers (including floating point). For string keys an <code>equal</code> test can be used,


<syntaxhighlight lang=Lisp>(setq my-table (make-hash-table :test 'equal))
<syntaxhighlight lang="lisp">(setq my-table (make-hash-table :test 'equal))
(puthash "key" 123 my-table)</syntaxhighlight>
(puthash "key" 123 my-table)</syntaxhighlight>


Line 2,843: Line 2,843:
=={{header|Erlang}}==
=={{header|Erlang}}==
Erlang offers several associative array type data structures, this example uses the dictionary data structure.
Erlang offers several associative array type data structures, this example uses the dictionary data structure.
<syntaxhighlight lang=erlang>
<syntaxhighlight lang="erlang">
-module(assoc).
-module(assoc).
-compile([export_all]).
-compile([export_all]).
Line 2,870: Line 2,870:
=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
.NET 3.5 Generic Dictionary (mutable)
.NET 3.5 Generic Dictionary (mutable)
<syntaxhighlight lang=fsharp>
<syntaxhighlight lang="fsharp">
let dic = System.Collections.Generic.Dictionary<string,string>() ;;
let dic = System.Collections.Generic.Dictionary<string,string>() ;;
dic.Add("key","val") ;
dic.Add("key","val") ;
Line 2,876: Line 2,876:
</syntaxhighlight>
</syntaxhighlight>
Functional dictionary (immutable)
Functional dictionary (immutable)
<syntaxhighlight lang=fsharp>
<syntaxhighlight lang="fsharp">
let d = [("key","val");("other key","other val")] |> Map.ofList
let d = [("key","val");("other key","other val")] |> Map.ofList
let newd = d.Add("new key","new val")
let newd = d.Add("new key","new val")
Line 2,889: Line 2,889:
Associative mappings follow the associative protocol. See [http://docs.factorcode.org/content/article-assocs-protocol.html the docs].
Associative mappings follow the associative protocol. See [http://docs.factorcode.org/content/article-assocs-protocol.html the docs].
Here's an example using a hashtable that can be run in the listener :
Here's an example using a hashtable that can be run in the listener :
<syntaxhighlight lang=factor>H{ { "one" 1 } { "two" 2 } }
<syntaxhighlight lang="factor">H{ { "one" 1 } { "two" 2 } }
{ [ "one" swap at . ]
{ [ "one" swap at . ]
[ 2 swap value-at . ]
[ 2 swap value-at . ]
Line 2,900: Line 2,900:
Associative arrays are called 'maps' in Fantom:
Associative arrays are called 'maps' in Fantom:


<syntaxhighlight lang=fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 2,925: Line 2,925:
The Forth dictionary is normally only used for function and symbol definitions, but you can also define separate ''wordlists'' for holding functions or data. There is no special syntax in the language for this, but you can define your own. All of Forth's defining words are available for adding things to the wordlist, but CREATE is most generic.
The Forth dictionary is normally only used for function and symbol definitions, but you can also define separate ''wordlists'' for holding functions or data. There is no special syntax in the language for this, but you can define your own. All of Forth's defining words are available for adding things to the wordlist, but CREATE is most generic.


<syntaxhighlight lang=forth>: get ( key len table -- data ) \ 0 if not present
<syntaxhighlight lang="forth">: get ( key len table -- data ) \ 0 if not present
search-wordlist if
search-wordlist if
>body @
>body @
Line 2,953: Line 2,953:


Hashtable for mapping strings to integer
Hashtable for mapping strings to integer
<syntaxhighlight lang=forth>include ffl/hct.fs
<syntaxhighlight lang="forth">include ffl/hct.fs


\ Create a hash table 'table' in the dictionary with a starting size of 10
\ Create a hash table 'table' in the dictionary with a starting size of 10
Line 2,975: Line 2,975:


Similar functionality is available in 4tH. A binary search is applied to search values, hence hashtables can be quite compact.
Similar functionality is available in 4tH. A binary search is applied to search values, hence hashtables can be quite compact.
<lang>include lib/hash.4th
<syntaxhighlight lang="text">include lib/hash.4th
include lib/hashkey.4th
include lib/hashkey.4th
Line 3,002: Line 3,002:
=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Uses unions to store the keys and associated values, and FreeBASIC's ability to resize arrays makes adding new entries easy.
Uses unions to store the keys and associated values, and FreeBASIC's ability to resize arrays makes adding new entries easy.
<syntaxhighlight lang=freebasic>#define max(a, b) Iif(a>b,a,b)
<syntaxhighlight lang="freebasic">#define max(a, b) Iif(a>b,a,b)


enum datatype
enum datatype
Line 3,079: Line 3,079:
=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
FPC 3.2.0.+. Similar to Delphi.
FPC 3.2.0.+. Similar to Delphi.
<syntaxhighlight lang=pascal>program AssociativeArrayCreation;
<syntaxhighlight lang="pascal">program AssociativeArrayCreation;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
Line 3,097: Line 3,097:
end.</syntaxhighlight>
end.</syntaxhighlight>
FPC 2.4+. Using FGL instead of rtl-generics:
FPC 2.4+. Using FGL instead of rtl-generics:
<syntaxhighlight lang=pascal>program AssociativeArrayCreation;
<syntaxhighlight lang="pascal">program AssociativeArrayCreation;
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
{$MODE DELPHI}
{$MODE DELPHI}
Line 3,116: Line 3,116:


=={{header|Futhark}}==
=={{header|Futhark}}==
<syntaxhighlight lang=futhark>let associative_array = {key1=1,key2=2}</syntaxhighlight>
<syntaxhighlight lang="futhark">let associative_array = {key1=1,key2=2}</syntaxhighlight>


=={{header|Gambas}}==
=={{header|Gambas}}==
Line 3,123: Line 3,123:
=={{header|Go}}==
=={{header|Go}}==
Allowable key types are those with == and != operators. This includes is boolean, numeric, string, pointer, channel, and interface types. It also includes structs and arrays containing only these types. Disallowed as map keys are all slice, function, and map types.
Allowable key types are those with == and != operators. This includes is boolean, numeric, string, pointer, channel, and interface types. It also includes structs and arrays containing only these types. Disallowed as map keys are all slice, function, and map types.
<syntaxhighlight lang=go>// declare a nil map variable, for maps from string to int
<syntaxhighlight lang="go">// declare a nil map variable, for maps from string to int
var x map[string]int
var x map[string]int


Line 3,149: Line 3,149:
=={{header|Gosu}}==
=={{header|Gosu}}==
As an OOP language with generics Gosu can use any variety of Map classes. In addition Gosu provides associative array syntax for all objects.
As an OOP language with generics Gosu can use any variety of Map classes. In addition Gosu provides associative array syntax for all objects.
<syntaxhighlight lang=javascript>// empty map
<syntaxhighlight lang="javascript">// empty map
var emptyMap = new HashMap<String, Integer>()
var emptyMap = new HashMap<String, Integer>()


Line 3,187: Line 3,187:
=={{header|Groovy}}==
=={{header|Groovy}}==
Create an empty map and add values
Create an empty map and add values
<syntaxhighlight lang=groovy>map = [:]
<syntaxhighlight lang="groovy">map = [:]
map[7] = 7
map[7] = 7
map['foo'] = 'foovalue'
map['foo'] = 'foovalue'
Line 3,199: Line 3,199:


Create a pre-populated map and verify values
Create a pre-populated map and verify values
<syntaxhighlight lang=groovy>map = [7:7, foo:'foovalue', bar:'barvalue', moo:'moovalue']
<syntaxhighlight lang="groovy">map = [7:7, foo:'foovalue', bar:'barvalue', moo:'moovalue']


assert 7 == map[7]
assert 7 == map[7]
Line 3,208: Line 3,208:
=={{header|Harbour}}==
=={{header|Harbour}}==
Create an empty array and add values:
Create an empty array and add values:
<syntaxhighlight lang=visualfoxpro>arr := { => }
<syntaxhighlight lang="visualfoxpro">arr := { => }
arr[ 10 ] := "Val_10"
arr[ 10 ] := "Val_10"
arr[ "foo" ] := "foovalue"</syntaxhighlight>
arr[ "foo" ] := "foovalue"</syntaxhighlight>
Create and initialize array:
Create and initialize array:
<syntaxhighlight lang=visualfoxpro>arr := hb_Hash( 10, "Val_10", "foo", "foovalue" )
<syntaxhighlight lang="visualfoxpro">arr := hb_Hash( 10, "Val_10", "foo", "foovalue" )
// or
// or
arr := { 10 => "Val_10", "foo" => "foovalue" }</syntaxhighlight>
arr := { 10 => "Val_10", "foo" => "foovalue" }</syntaxhighlight>
Line 3,219: Line 3,219:
Binary trees:
Binary trees:
{{works with|GHC}}
{{works with|GHC}}
<syntaxhighlight lang=haskell>import Data.Map
<syntaxhighlight lang="haskell">import Data.Map


dict = fromList [("key1","val1"), ("key2","val2")]
dict = fromList [("key1","val1"), ("key2","val2")]
Line 3,227: Line 3,227:


It is also possible to use association lists (lists of pairs). It is inefficient (O(n) lookup), but simple.
It is also possible to use association lists (lists of pairs). It is inefficient (O(n) lookup), but simple.
<syntaxhighlight lang=haskell>dict = [("key1","val1"), ("key2","val2")]
<syntaxhighlight lang="haskell">dict = [("key1","val1"), ("key2","val2")]


ans = lookup "key2" dict -- evaluates to Just "val2"
ans = lookup "key2" dict -- evaluates to Just "val2"
Line 3,237: Line 3,237:


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<syntaxhighlight lang=hexiscript>let d dict 2 # Initial estimated size
<syntaxhighlight lang="hexiscript">let d dict 2 # Initial estimated size
let d["test"] "test" # Strings can be used as index
let d["test"] "test" # Strings can be used as index
let d[123] 123 # Integers can also be used as index
let d[123] 123 # Integers can also be used as index
Line 3,247: Line 3,247:
Icon and Unicon associative arrays are called tables. Any value may be used as a key including complex structures. Tables can have default values and they have no inherent size limitation growing from empty to whatever size is needed.
Icon and Unicon associative arrays are called tables. Any value may be used as a key including complex structures. Tables can have default values and they have no inherent size limitation growing from empty to whatever size is needed.


<syntaxhighlight lang=icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
local t
local t
t := table()
t := table()
Line 3,258: Line 3,258:


===Static relation===
===Static relation===
<syntaxhighlight lang=inform7>Hash Bar is a room.
<syntaxhighlight lang="inform7">Hash Bar is a room.


Connection relates various texts to one number. The verb to be connected to implies the connection relation.
Connection relates various texts to one number. The verb to be connected to implies the connection relation.
Line 3,278: Line 3,278:


===Dynamic relation===
===Dynamic relation===
<syntaxhighlight lang=inform7>Hash Bar is a room.
<syntaxhighlight lang="inform7">Hash Bar is a room.


When play begins:
When play begins:
Line 3,295: Line 3,295:


=={{header|Ioke}}==
=={{header|Ioke}}==
<syntaxhighlight lang=ioke>{a: "a", b: "b"}</syntaxhighlight>
<syntaxhighlight lang="ioke">{a: "a", b: "b"}</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 3,303: Line 3,303:
However, it's also possible to use the symbol table itself to hold the names. The symbol table has limitations (can only accept syntactically valid names), but we can turn arbitrary strings into valid symbols using base 62 encode and prefixing with a letter (hypothetically speaking, base 64 encode would let us build longer names than base 62, because of computational complexity issues - but the J symbol table also comes with a name length limit - 255 characters - and does not support 64 different characters in names):
However, it's also possible to use the symbol table itself to hold the names. The symbol table has limitations (can only accept syntactically valid names), but we can turn arbitrary strings into valid symbols using base 62 encode and prefixing with a letter (hypothetically speaking, base 64 encode would let us build longer names than base 62, because of computational complexity issues - but the J symbol table also comes with a name length limit - 255 characters - and does not support 64 different characters in names):


<syntaxhighlight lang=J>coclass 'assocArray'
<syntaxhighlight lang="j">coclass 'assocArray'
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i.
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i.
get=: ".@encode
get=: ".@encode
Line 3,311: Line 3,311:
Example use:
Example use:


<syntaxhighlight lang=j> example=: conew 'assocArray'
<syntaxhighlight lang="j"> example=: conew 'assocArray'
'foo' set__example 1 2 3
'foo' set__example 1 2 3
1 2 3
1 2 3
Line 3,331: Line 3,331:


Defining the Map:
Defining the Map:
<syntaxhighlight lang=java5>Map<String, Integer> map = new HashMap<String, Integer>();
<syntaxhighlight lang="java5">Map<String, Integer> map = new HashMap<String, Integer>();
map.put("foo", 5);
map.put("foo", 5);
map.put("bar", 10);
map.put("bar", 10);
Line 3,339: Line 3,339:


Initializing a Map as a class member:
Initializing a Map as a class member:
<syntaxhighlight lang=java5>public static Map<String, Integer> map = new HashMap<String, Integer>(){{
<syntaxhighlight lang="java5">public static Map<String, Integer> map = new HashMap<String, Integer>(){{
put("foo", 5);
put("foo", 5);
put("bar", 10);
put("bar", 10);
Line 3,346: Line 3,346:
}};</syntaxhighlight>
}};</syntaxhighlight>
Retrieving a value:
Retrieving a value:
<syntaxhighlight lang=java5>map.get("foo"); // => 6
<syntaxhighlight lang="java5">map.get("foo"); // => 6
map.get("invalid"); // => null</syntaxhighlight>
map.get("invalid"); // => null</syntaxhighlight>
Note that it is possible to put <code>null</code> as a value, so <code>null</code> being returned by <code>get</code> is not sufficient for determining that the key is not in the <code>Map</code>. There is a <code>containsKey</code> method for that.
Note that it is possible to put <code>null</code> as a value, so <code>null</code> being returned by <code>get</code> is not sufficient for determining that the key is not in the <code>Map</code>. There is a <code>containsKey</code> method for that.


Iterate over keys:
Iterate over keys:
<syntaxhighlight lang=java5>for (String key: map.keySet())
<syntaxhighlight lang="java5">for (String key: map.keySet())
System.out.println(key);</syntaxhighlight>
System.out.println(key);</syntaxhighlight>
Iterate over values:
Iterate over values:
<syntaxhighlight lang=java5>for (int value: map.values())
<syntaxhighlight lang="java5">for (int value: map.values())
System.out.println(value);</syntaxhighlight>
System.out.println(value);</syntaxhighlight>
Iterate over key, value pairs:
Iterate over key, value pairs:
<syntaxhighlight lang=java5>for (Map.Entry<String, Integer> entry: map.entrySet())
<syntaxhighlight lang="java5">for (Map.Entry<String, Integer> entry: map.entrySet())
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>


Line 3,364: Line 3,364:


Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name. Using quotes on property names avoids potential collisions with reserved JavaScript key words.
Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name. Using quotes on property names avoids potential collisions with reserved JavaScript key words.
<syntaxhighlight lang=javascript>var assoc = {};
<syntaxhighlight lang="javascript">var assoc = {};


assoc['foo'] = 'bar';
assoc['foo'] = 'bar';
Line 3,388: Line 3,388:


ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings.
ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings.
<syntaxhighlight lang=javascript>var map = new Map(),
<syntaxhighlight lang="javascript">var map = new Map(),
fn = function () {},
fn = function () {},
obj = {};
obj = {};
Line 3,414: Line 3,414:
===Associative Arrays with String-Valued Keys===
===Associative Arrays with String-Valued Keys===
In jq, JSON objects can be used as associative arrays, it being understood that only strings can be used as keys. To avoid confusion, for the remainder of this section, we refer to JSON objects as such. Their type in jq is "object".
In jq, JSON objects can be used as associative arrays, it being understood that only strings can be used as keys. To avoid confusion, for the remainder of this section, we refer to JSON objects as such. Their type in jq is "object".
<syntaxhighlight lang=jq># An empty object:
<syntaxhighlight lang="jq"># An empty object:
{}
{}


Line 3,440: Line 3,440:
In this subsection, we define addKey(key;value), getKey(key), and removeKey(key)
In this subsection, we define addKey(key;value), getKey(key), and removeKey(key)
to operate on a hash table for which the keys may be any JSON entities. This is done by defining a collisionless hash function.
to operate on a hash table for which the keys may be any JSON entities. This is done by defining a collisionless hash function.
<syntaxhighlight lang=jq>def collisionless:
<syntaxhighlight lang="jq">def collisionless:
if type == "object" then with_entries(.value = (.value|collisionless))|tostring
if type == "object" then with_entries(.value = (.value|collisionless))|tostring
elif type == "array" then map(collisionless)|tostring
elif type == "array" then map(collisionless)|tostring
Line 3,456: Line 3,456:
def removeKey(key): delpaths( [ [key|collisionless] ] );</syntaxhighlight>
def removeKey(key): delpaths( [ [key|collisionless] ] );</syntaxhighlight>
'''Example''':
'''Example''':
<syntaxhighlight lang=jq>{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</syntaxhighlight>
<syntaxhighlight lang="jq">{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</syntaxhighlight>
produces:
produces:
<syntaxhighlight lang=sh>"two"</syntaxhighlight>
<syntaxhighlight lang="sh">"two"</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript. jsish warns of duplicate ''var'', in this case the ''assoc'' variable is reused.
From Javascript. jsish warns of duplicate ''var'', in this case the ''assoc'' variable is reused.
<syntaxhighlight lang=javascript>var assoc = {};
<syntaxhighlight lang="javascript">var assoc = {};
assoc['foo'] = 'bar';
assoc['foo'] = 'bar';
Line 3,503: Line 3,503:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
We build dictionaries associating to some characters their code points, by listing the key/value pairs, through a dictionary comprehension, by creating an empty dictionary and filling it, by using the specific syntax associated to typed dictionaries.
We build dictionaries associating to some characters their code points, by listing the key/value pairs, through a dictionary comprehension, by creating an empty dictionary and filling it, by using the specific syntax associated to typed dictionaries.
<syntaxhighlight lang=julia>dict = Dict('a' => 97, 'b' => 98) # list keys/values
<syntaxhighlight lang="julia">dict = Dict('a' => 97, 'b' => 98) # list keys/values
# Dict{Char,Int64} with 2 entries:
# Dict{Char,Int64} with 2 entries:
# 'b' => 98
# 'b' => 98
Line 3,533: Line 3,533:
=={{header|K}}==
=={{header|K}}==
Keys in a dictionary must be symbols (`symbol).
Keys in a dictionary must be symbols (`symbol).
<syntaxhighlight lang=K> / creating an dictionary
<syntaxhighlight lang="k"> / creating an dictionary
d1:.((`foo;1); (`bar;2); (`baz;3))
d1:.((`foo;1); (`bar;2); (`baz;3))


Line 3,541: Line 3,541:
Another approach.
Another approach.
<syntaxhighlight lang=K> d2: .() / create empty dictionary
<syntaxhighlight lang="k"> d2: .() / create empty dictionary
d2[`"zero"]:0
d2[`"zero"]:0
d2[`"one"]:1
d2[`"one"]:1
Line 3,552: Line 3,552:


Extracting the keys and values.
Extracting the keys and values.
<syntaxhighlight lang=K> !d2 / the keys
<syntaxhighlight lang="k"> !d2 / the keys
`zero `one `two
`zero `one `two


Line 3,560: Line 3,560:
=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<syntaxhighlight lang=scala>fun main(args: Array<String>) {
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
// map definition:
// map definition:
val map = mapOf("foo" to 5,
val map = mapOf("foo" to 5,
Line 3,589: Line 3,589:
=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
Associative arrays are not currently built in the JS.js kernel of lambdatalk but are added via the lib_hash library page.
Associative arrays are not currently built in the JS.js kernel of lambdatalk but are added via the lib_hash library page.
<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">


1) a (currently) reduced set of functions:
1) a (currently) reduced set of functions:
Line 3,650: Line 3,650:


=={{header|Lang5}}==
=={{header|Lang5}}==
<syntaxhighlight lang=lang5>: dip swap '_ set execute _ ; : nip swap drop ;
<syntaxhighlight lang="lang5">: dip swap '_ set execute _ ; : nip swap drop ;
: first 0 extract nip ; : second 1 extract nip ;
: first 0 extract nip ; : second 1 extract nip ;


Line 3,671: Line 3,671:
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1.
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1.


<syntaxhighlight lang=langur>var .hash = h{1: "abc", "1": 789}
<syntaxhighlight lang="langur">var .hash = h{1: "abc", "1": 789}


# may assign with existing or non-existing hash key (if hash is mutable)
# may assign with existing or non-existing hash key (if hash is mutable)
Line 3,692: Line 3,692:


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso>// In Lasso associative arrays are called maps
<syntaxhighlight lang="lasso">// In Lasso associative arrays are called maps


// Define an empty map
// Define an empty map
Line 3,732: Line 3,732:


=={{header|LFE}}==
=={{header|LFE}}==
<syntaxhighlight lang=lisp>
<syntaxhighlight lang="lisp">
(let* ((my-dict (: dict new))
(let* ((my-dict (: dict new))
(my-dict (: dict store 'key-1 '"value 1" my-dict))
(my-dict (: dict store 'key-1 '"value 1" my-dict))
Line 3,743: Line 3,743:
=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Needs the sublist library from http://basic.wikispaces.com/SubList+Library since LB does not have built-in associative arrays.
Needs the sublist library from http://basic.wikispaces.com/SubList+Library since LB does not have built-in associative arrays.
<syntaxhighlight lang=lb>
<syntaxhighlight lang="lb">
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255"
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255"
data "my fave", "220 120 120", "black", "0 0 0"
data "my fave", "220 120 120", "black", "0 0 0"
Line 3,760: Line 3,760:


=={{header|Lingo}}==
=={{header|Lingo}}==
<syntaxhighlight lang=lingo>props = [#key1: "value1", #key2: "value2"]
<syntaxhighlight lang="lingo">props = [#key1: "value1", #key2: "value2"]


put props[#key2]
put props[#key2]
Line 3,773: Line 3,773:
=={{header|LiveCode}}==
=={{header|LiveCode}}==
Livecode arrays are only associative, but can be accessed by ordinal if they are used as the key.
Livecode arrays are only associative, but can be accessed by ordinal if they are used as the key.
<syntaxhighlight lang=LiveCode>command assocArray
<syntaxhighlight lang="livecode">command assocArray
local tArray
local tArray
put "value 1" into tArray["key 1"]
put "value 1" into tArray["key 1"]
Line 3,784: Line 3,784:
end assocArray</syntaxhighlight>
end assocArray</syntaxhighlight>
Output
Output
<syntaxhighlight lang=LiveCode>number of elements: 3
<syntaxhighlight lang="livecode">number of elements: 3
length of item 3: 5
length of item 3: 5
keys: key numbers
keys: key numbers
Line 3,792: Line 3,792:
=={{header|Logo}}==
=={{header|Logo}}==
[[UCB Logo]] has "property lists" which associate names with values. They have their own namespace.
[[UCB Logo]] has "property lists" which associate names with values. They have their own namespace.
<syntaxhighlight lang=logo>pprop "animals "cat 5
<syntaxhighlight lang="logo">pprop "animals "cat 5
pprop "animals "dog 4
pprop "animals "dog 4
pprop "animals "mouse 11
pprop "animals "mouse 11
Line 3,801: Line 3,801:
=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
BUKKITs are associative arrays
BUKKITs are associative arrays
<syntaxhighlight lang=lolcode>HAI 1.2
<syntaxhighlight lang="lolcode">HAI 1.2
I HAS A Hash ITZ A BUKKIT
I HAS A Hash ITZ A BUKKIT
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript
Line 3,813: Line 3,813:
=={{header|Lua}}==
=={{header|Lua}}==
Lua tables are Hashes
Lua tables are Hashes
<syntaxhighlight lang=lua>hash = {}
<syntaxhighlight lang="lua">hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
hash[ "key-2" ] = 1
Line 3,821: Line 3,821:
=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Μ2000 has Inventory object to use it as a Map. All keys converted to strings. If a key has no value then key is the value until we place one. A special type of Inventory is the Inventory Queue, where we can use same keys, and we can't delete except from the last append.
Μ2000 has Inventory object to use it as a Map. All keys converted to strings. If a key has no value then key is the value until we place one. A special type of Inventory is the Inventory Queue, where we can use same keys, and we can't delete except from the last append.
<syntaxhighlight lang=M2000 Interpreter>
<syntaxhighlight lang="m2000 interpreter">
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There"
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There"
Print len(A)
Print len(A)
Line 3,847: Line 3,847:
=={{header|Maple}}==
=={{header|Maple}}==
Maple tables are hashed arrays. A table can be constructed by using the table constructor.
Maple tables are hashed arrays. A table can be constructed by using the table constructor.
<syntaxhighlight lang=Maple>> T := table( [ (2,3) = 4, "foo" = 1, sin(x) = cos(x) ] );
<syntaxhighlight lang="maple">> T := table( [ (2,3) = 4, "foo" = 1, sin(x) = cos(x) ] );
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4])
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4])


Line 3,859: Line 3,859:
1</syntaxhighlight>
1</syntaxhighlight>
New entries are added by assignment.
New entries are added by assignment.
<syntaxhighlight lang=Maple>> T[ "bar" ] := 2;
<syntaxhighlight lang="maple">> T[ "bar" ] := 2;
T["bar"] := 2
T["bar"] := 2


Line 3,865: Line 3,865:
2</syntaxhighlight>
2</syntaxhighlight>
Entries can be removed as follows.
Entries can be removed as follows.
<syntaxhighlight lang=Maple>> T[ "foo" ] := evaln( T[ "foo" ] );
<syntaxhighlight lang="maple">> T[ "foo" ] := evaln( T[ "foo" ] );
T["foo"] := T["foo"]
T["foo"] := T["foo"]


Line 3,873: Line 3,873:


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica>a[2] = "string"; a["sometext"] = 23;</syntaxhighlight>
<syntaxhighlight lang="mathematica">a[2] = "string"; a["sometext"] = 23;</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
Line 3,880: Line 3,880:
Associative arrays are called structs. The following methods of creating hash are equivalent.
Associative arrays are called structs. The following methods of creating hash are equivalent.


<syntaxhighlight lang=MATLAB> hash.a = 1;
<syntaxhighlight lang="matlab"> hash.a = 1;
hash.b = 2;
hash.b = 2;
hash.C = [3,4,5]; </syntaxhighlight>
hash.C = [3,4,5]; </syntaxhighlight>
alternatively
alternatively
<syntaxhighlight lang=MATLAB> hash = [];
<syntaxhighlight lang="matlab"> hash = [];
hash = setfield(hash,'a',1);
hash = setfield(hash,'a',1);
hash = setfield(hash,'b',2);
hash = setfield(hash,'b',2);
hash = setfield(hash,'C',[3,4,5]); </syntaxhighlight>
hash = setfield(hash,'C',[3,4,5]); </syntaxhighlight>
or
or
<syntaxhighlight lang=MATLAB> hash.('a') = 1;
<syntaxhighlight lang="matlab"> hash.('a') = 1;
hash.('b') = 2;
hash.('b') = 2;
hash.('C') = [3,4,5]; </syntaxhighlight>
hash.('C') = [3,4,5]; </syntaxhighlight>
Line 3,905: Line 3,905:
===MATLAB only: containers.Map===
===MATLAB only: containers.Map===
Use of containers.Map removes some restrictions on key types that structs have. Keys can all be numeric or all be strings. Values can be of any type. Key and value types cannot be changed after creation of the containers.Map object.
Use of containers.Map removes some restrictions on key types that structs have. Keys can all be numeric or all be strings. Values can be of any type. Key and value types cannot be changed after creation of the containers.Map object.
<syntaxhighlight lang=MATLAB>m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</syntaxhighlight>
<syntaxhighlight lang="matlab">m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</syntaxhighlight>
is equivalent to
is equivalent to
<syntaxhighlight lang=MATLAB>m = containers.Map;
<syntaxhighlight lang="matlab">m = containers.Map;
m('a') = 1;
m('a') = 1;
m('b') = 2;
m('b') = 2;
m('C') = 3;</syntaxhighlight>
m('C') = 3;</syntaxhighlight>
since the KeyType defaults to 'char'. For numeric keys, the key and value types must be specified at creation.
since the KeyType defaults to 'char'. For numeric keys, the key and value types must be specified at creation.
<syntaxhighlight lang=MATLAB>m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</syntaxhighlight>
<syntaxhighlight lang="matlab">m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</syntaxhighlight>
is equivalent to
is equivalent to
<syntaxhighlight lang=MATLAB>m = containers.Map('KeyType', 'double', 'ValueType', 'any');
<syntaxhighlight lang="matlab">m = containers.Map('KeyType', 'double', 'ValueType', 'any');
m(51) = 'fiftyone';
m(51) = 'fiftyone';
m(72) = 'seventytwo';
m(72) = 'seventytwo';
Line 3,933: Line 3,933:


=={{header|Maxima}}==
=={{header|Maxima}}==
<syntaxhighlight lang=maxima>/* No need to declare anything, undeclared arrays are hashed */
<syntaxhighlight lang="maxima">/* No need to declare anything, undeclared arrays are hashed */


h[1]: 6;
h[1]: 6;
Line 3,943: Line 3,943:
=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<syntaxhighlight lang=min>{1 :one 2 :two 3 :three}</syntaxhighlight>
<syntaxhighlight lang="min">{1 :one 2 :two 3 :three}</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
A map literal in MiniScript is enclosed in curly braces, with key:value pairs separated by commas. Keys and values may be any type. Retrieval or assignment is by putting the key in square brackets. As syntactic sugar, when a string key follows the rules of a MiniScript identifier (starts with a letter and contains only letters, numbers, and underscores), you may also access it with dot syntax.
A map literal in MiniScript is enclosed in curly braces, with key:value pairs separated by commas. Keys and values may be any type. Retrieval or assignment is by putting the key in square brackets. As syntactic sugar, when a string key follows the rules of a MiniScript identifier (starts with a letter and contains only letters, numbers, and underscores), you may also access it with dot syntax.
<syntaxhighlight lang=MiniScript>map = { 3: "test", "foo": 42 }
<syntaxhighlight lang="miniscript">map = { 3: "test", "foo": 42 }


print map[3]
print map[3]
Line 3,958: Line 3,958:
=={{header|Nemerle}}==
=={{header|Nemerle}}==
This demonstrates two of several constructors, initializing the hashtable with a list of tuples or just specifying an initial capacity.
This demonstrates two of several constructors, initializing the hashtable with a list of tuples or just specifying an initial capacity.
<syntaxhighlight lang=Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections;
Line 3,977: Line 3,977:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref symbols
options replace format comments java crossref symbols
Line 3,997: Line 3,997:


=={{header|Nim}}==
=={{header|Nim}}==
<syntaxhighlight lang=nim>import tables
<syntaxhighlight lang="nim">import tables


var
var
Line 4,045: Line 4,045:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with| oo2c Version 2}}
{{works with| oo2c Version 2}}
<syntaxhighlight lang=oberon2>
<syntaxhighlight lang="oberon2">
MODULE AssociativeArray;
MODULE AssociativeArray;
IMPORT
IMPORT
Line 4,094: Line 4,094:


=== Associative map===
=== Associative map===
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
# create map
# create map
map := StringMap->New();
map := StringMap->New();
Line 4,108: Line 4,108:


===Hash table===
===Hash table===
<syntaxhighlight lang=objeck>
<syntaxhighlight lang="objeck">
# create map
# create map
map := StringHash->New();
map := StringHash->New();
Line 4,125: Line 4,125:


You can use a NSDictionary to create an immutable hash. A dictionary can contain only objects; if you want store non objects like integer, you have to box it in NSNumber.
You can use a NSDictionary to create an immutable hash. A dictionary can contain only objects; if you want store non objects like integer, you have to box it in NSNumber.
<syntaxhighlight lang=objc>NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
<syntaxhighlight lang="objc">NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joe Doe", @"name",
@"Joe Doe", @"name",
[NSNumber numberWithUnsignedInt:42], @"age",
[NSNumber numberWithUnsignedInt:42], @"age",
Line 4,132: Line 4,132:


The same as the above with the new literal syntax in clang 3.1+ / Apple LLVM Compiler 4.0+ (XCode 4.4+) :
The same as the above with the new literal syntax in clang 3.1+ / Apple LLVM Compiler 4.0+ (XCode 4.4+) :
<syntaxhighlight lang=objc>NSDictionary *dict = @{
<syntaxhighlight lang="objc">NSDictionary *dict = @{
@"name": @"Joe Doe",
@"name": @"Joe Doe",
@"age": @42,
@"age": @42,
Line 4,139: Line 4,139:


To create a mutable dictionary, use NSMutableDictionary:
To create a mutable dictionary, use NSMutableDictionary:
<syntaxhighlight lang=objc>NSMutableDictionary *dict = [NSMutableDictionary dictionary];
<syntaxhighlight lang="objc">NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"Joe Doe" forKey:@"name"];
[dict setObject:@"Joe Doe" forKey:@"name"];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"age"];</syntaxhighlight>
[dict setObject:[NSNumber numberWithInt:42] forKey:@"age"];</syntaxhighlight>


You can access value with objectForKey:. If a key does not exists, nil is returned.
You can access value with objectForKey:. If a key does not exists, nil is returned.
<syntaxhighlight lang=objc>NSString *name = [dict objectForKey:@"name"];
<syntaxhighlight lang="objc">NSString *name = [dict objectForKey:@"name"];
unsigned age = [dict objectForKey:@"age"] unsignedIntValue];
unsigned age = [dict objectForKey:@"age"] unsignedIntValue];
id missing = [dict objectForKey:@"missing"];</syntaxhighlight>
id missing = [dict objectForKey:@"missing"];</syntaxhighlight>
Line 4,151: Line 4,151:
===Hash table===
===Hash table===
A simple idiom to create a hash table mapping strings to integers:
A simple idiom to create a hash table mapping strings to integers:
<syntaxhighlight lang=ocaml>let hash = Hashtbl.create 0;;
<syntaxhighlight lang="ocaml">let hash = Hashtbl.create 0;;
List.iter (fun (key, value) -> Hashtbl.add hash key value)
List.iter (fun (key, value) -> Hashtbl.add hash key value)
["foo", 5; "bar", 10; "baz", 15];;</syntaxhighlight>
["foo", 5; "bar", 10; "baz", 15];;</syntaxhighlight>
To retrieve a value:
To retrieve a value:
<syntaxhighlight lang=ocaml>let bar = Hashtbl.find hash "bar";; (* bar = 10 *)</syntaxhighlight>
<syntaxhighlight lang="ocaml">let bar = Hashtbl.find hash "bar";; (* bar = 10 *)</syntaxhighlight>
To retrieve a value, returning a default if the key is not found:
To retrieve a value, returning a default if the key is not found:
<syntaxhighlight lang=ocaml>let quux = try Hashtbl.find hash "quux" with Not_found -> some_value;;</syntaxhighlight>
<syntaxhighlight lang="ocaml">let quux = try Hashtbl.find hash "quux" with Not_found -> some_value;;</syntaxhighlight>


===Binary tree===
===Binary tree===
A simple idiom to create a persistent binary tree mapping strings to integers:
A simple idiom to create a persistent binary tree mapping strings to integers:
<syntaxhighlight lang=ocaml>module String = struct
<syntaxhighlight lang="ocaml">module String = struct
type t = string
type t = string
let compare = Pervasives.compare
let compare = Pervasives.compare
Line 4,174: Line 4,174:
;;</syntaxhighlight>
;;</syntaxhighlight>
To retrieve a value:
To retrieve a value:
<syntaxhighlight lang=ocaml>let bar = StringMap.find "bar" map;; (* bar = 10 *)</syntaxhighlight>
<syntaxhighlight lang="ocaml">let bar = StringMap.find "bar" map;; (* bar = 10 *)</syntaxhighlight>
To retrieve a value, returning a default if the key is not found:
To retrieve a value, returning a default if the key is not found:
<syntaxhighlight lang=ocaml>let quux = try StringMap.find "quux" map with Not_found -> some_value;;</syntaxhighlight>
<syntaxhighlight lang="ocaml">let quux = try StringMap.find "quux" map with Not_found -> some_value;;</syntaxhighlight>
===Association list===
===Association list===
Some list functions allow you to use a list as an associative map, although the access time is O(N) so a Hashtbl or binary tree should be used for larger data-sets.
Some list functions allow you to use a list as an associative map, although the access time is O(N) so a Hashtbl or binary tree should be used for larger data-sets.
<syntaxhighlight lang=Ocaml>let dict = ["foo", 5; "bar", 10; "baz", 15]
<syntaxhighlight lang="ocaml">let dict = ["foo", 5; "bar", 10; "baz", 15]


(* retrieve value *)
(* retrieve value *)
Line 4,192: Line 4,192:
You can use only values as keys (atomic numbers, constants) and, as exception, symbols (symbols are references, but unique). No strings, lists, vectors and other objects can be used directly. In such cases use hashes or similar mechanisms.
You can use only values as keys (atomic numbers, constants) and, as exception, symbols (symbols are references, but unique). No strings, lists, vectors and other objects can be used directly. In such cases use hashes or similar mechanisms.


<syntaxhighlight lang=scheme>
<syntaxhighlight lang="scheme">
;;; empty associative array
;;; empty associative array
#empty
#empty
Line 4,237: Line 4,237:


Defining the map:
Defining the map:
<syntaxhighlight lang=ooRexx>map = .directory~new
<syntaxhighlight lang="oorexx">map = .directory~new
map["foo"] = 5
map["foo"] = 5
map["bar"] = 10
map["bar"] = 10
Line 4,246: Line 4,246:


Retrieving a value:
Retrieving a value:
<syntaxhighlight lang=ooRexx>item = map["foo"] -- => 6
<syntaxhighlight lang="oorexx">item = map["foo"] -- => 6
item = map["invalid"] -- => .nil</syntaxhighlight>
item = map["invalid"] -- => .nil</syntaxhighlight>
Note that it is possible to put <code>.nil</code> as a value, so <code>.nil</code> being returned as a value is not sufficient for determining that the key is not in the collection. There is a <code>hasIndex</code> method for that.
Note that it is possible to put <code>.nil</code> as a value, so <code>.nil</code> being returned as a value is not sufficient for determining that the key is not in the collection. There is a <code>hasIndex</code> method for that.


Iterate over keys:
Iterate over keys:
<syntaxhighlight lang=ooRexx>loop key over map
<syntaxhighlight lang="oorexx">loop key over map
say key
say key
end
end
</syntaxhighlight>
</syntaxhighlight>
Iterate over values:
Iterate over values:
<syntaxhighlight lang=ooRexx>loop value over map~allItems
<syntaxhighlight lang="oorexx">loop value over map~allItems
say value
say value
end
end
</syntaxhighlight>
</syntaxhighlight>
Iterate over key, value pairs:
Iterate over key, value pairs:
<syntaxhighlight lang=ooRexx>
<syntaxhighlight lang="oorexx">
s = map~supplier
s = map~supplier
loop while s~available
loop while s~available
Line 4,271: Line 4,271:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
Not very efficient but the 'find' method could be optimised very easily.
Not very efficient but the 'find' method could be optimised very easily.
<syntaxhighlight lang=oxygenbasic>
<syntaxhighlight lang="oxygenbasic">
def n 200
def n 200


Line 4,328: Line 4,328:
=={{header|Oz}}==
=={{header|Oz}}==
A mutable map is called a 'dictionary' in Oz:
A mutable map is called a 'dictionary' in Oz:
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
Dict = {Dictionary.new}
Dict = {Dictionary.new}
in
in
Line 4,339: Line 4,339:


'Records' can be consideres immutable maps:
'Records' can be consideres immutable maps:
<syntaxhighlight lang=oz>declare
<syntaxhighlight lang="oz">declare
Rec = name(foo:5 bar:10 baz:20)
Rec = name(foo:5 bar:10 baz:20)
in
in
Line 4,348: Line 4,348:


GP's associative arrays are called maps, and can be created like so:
GP's associative arrays are called maps, and can be created like so:
<syntaxhighlight lang=parigp>M = Map();</syntaxhighlight>
<syntaxhighlight lang="parigp">M = Map();</syntaxhighlight>
They can be used as follows:
They can be used as follows:
<syntaxhighlight lang=parigp>mapput(M, "key", "value");
<syntaxhighlight lang="parigp">mapput(M, "key", "value");
mapput(M, 17, "different value");
mapput(M, 17, "different value");
mapput(M, "key2", Pi);
mapput(M, "key2", Pi);
Line 4,362: Line 4,362:
===Hash===
===Hash===
Definition:
Definition:
<syntaxhighlight lang=perl># using => key does not need to be quoted unless it contains special chars
<syntaxhighlight lang="perl"># using => key does not need to be quoted unless it contains special chars
my %hash = (
my %hash = (
key1 => 'val1',
key1 => 'val1',
Line 4,379: Line 4,379:


Use:
Use:
<syntaxhighlight lang=perl>print $hash{key1};
<syntaxhighlight lang="perl">print $hash{key1};


$hash{key1} = 'val1';
$hash{key1} = 'val1';
Line 4,386: Line 4,386:
===HashRef===
===HashRef===
Definition:
Definition:
<syntaxhighlight lang=perl>my $hashref = {
<syntaxhighlight lang="perl">my $hashref = {
key1 => 'val1',
key1 => 'val1',
'key-2' => 2,
'key-2' => 2,
Line 4,394: Line 4,394:


Use:
Use:
<syntaxhighlight lang=perl>print $hashref->{key1};
<syntaxhighlight lang="perl">print $hashref->{key1};


$hashref->{key1} = 'val1';
$hashref->{key1} = 'val1';
Line 4,416: Line 4,416:
integer tid=new_dict(), and pass that as an additional (final) parameter to the other routines (taking care not to miss
integer tid=new_dict(), and pass that as an additional (final) parameter to the other routines (taking care not to miss
any). When you have no further use for it, an entire dictionary can be removed by invoking destroy_dict(tid).
any). When you have no further use for it, an entire dictionary can be removed by invoking destroy_dict(tid).
<!--<syntaxhighlight lang=Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
Line 4,429: Line 4,429:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


def getd /# dict key -- dict data #/
def getd /# dict key -- dict data #/
Line 4,466: Line 4,466:


=={{header|PHP}}==
=={{header|PHP}}==
<syntaxhighlight lang=php>$array = array();
<syntaxhighlight lang="php">$array = array();
$array = []; // Simpler form of array initialization
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
$array['foo'] = 'bar';
Line 4,489: Line 4,489:


===Iterate over key/value===
===Iterate over key/value===
<syntaxhighlight lang=php>foreach($array as $key => $value)
<syntaxhighlight lang="php">foreach($array as $key => $value)
{
{
echo "Key: $key Value: $value";
echo "Key: $key Value: $value";
Line 4,496: Line 4,496:
=={{header|Picat}}==
=={{header|Picat}}==
Associative arrays are called "map" in Picat.
Associative arrays are called "map" in Picat.
<syntaxhighlight lang=Picat>go =>
<syntaxhighlight lang="picat">go =>


% Create an empty map
% Create an empty map
Line 4,551: Line 4,551:
[http://software-lab.de/doc/refA.html#assoc association lists].
[http://software-lab.de/doc/refA.html#assoc association lists].


<syntaxhighlight lang=PicoLisp>(put 'A 'foo 5)
<syntaxhighlight lang="picolisp">(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'bar 10)
(put 'A 'baz 15)
(put 'A 'baz 15)
Line 4,580: Line 4,580:
''indices()'' and ''values()'' can be used to enumerate the contents
''indices()'' and ''values()'' can be used to enumerate the contents
of an existing mapping.
of an existing mapping.
<syntaxhighlight lang=Pike>
<syntaxhighlight lang="pike">
mapping m = ([ "apple": "fruit", 17: "seventeen" ]);
mapping m = ([ "apple": "fruit", 17: "seventeen" ]);
write("indices: %O\nvalues: %O\n17: %O\n",
write("indices: %O\nvalues: %O\n17: %O\n",
Line 4,602: Line 4,602:
Since any data type can be used nested structures of arbitrary size can
Since any data type can be used nested structures of arbitrary size can
be constructed.
be constructed.
<syntaxhighlight lang=Pike>
<syntaxhighlight lang="pike">
mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]);
mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]);
write("#ford: %O, #volvo: %O\n",
write("#ford: %O, #volvo: %O\n",
Line 4,614: Line 4,614:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang=pli>*process source xref attributes or(!);
<syntaxhighlight lang="pli">*process source xref attributes or(!);
assocarr: Proc Options(main);
assocarr: Proc Options(main);
Dcl 1 aa,
Dcl 1 aa,
Line 4,682: Line 4,682:


The following example code is a "record definition", which has nothing to do with associative arrays:-
The following example code is a "record definition", which has nothing to do with associative arrays:-
<syntaxhighlight lang=PL/SQL>DECLARE
<syntaxhighlight lang="pl/sql">DECLARE
type ThisIsNotAnAssocArrayType is record (
type ThisIsNotAnAssocArrayType is record (
myShape VARCHAR2(20),
myShape VARCHAR2(20),
Line 4,698: Line 4,698:


=={{header|Pop11}}==
=={{header|Pop11}}==
<syntaxhighlight lang=pop11>;;; Create expandable hash table of initial size 50 and with default
<syntaxhighlight lang="pop11">;;; Create expandable hash table of initial size 50 and with default
;;; value 0 (default value is returned when the item is absent).
;;; value 0 (default value is returned when the item is absent).
vars ht = newmapping([], 50, 0, true);
vars ht = newmapping([], 50, 0, true);
Line 4,722: Line 4,722:


=={{header|PostScript}}==
=={{header|PostScript}}==
<syntaxhighlight lang=postscript>
<syntaxhighlight lang="postscript">
<</a 100 /b 200 /c 300>>
<</a 100 /b 200 /c 300>>
dup /a get =
dup /a get =
Line 4,728: Line 4,728:


=={{header|Potion}}==
=={{header|Potion}}==
<syntaxhighlight lang=potion>mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)
<syntaxhighlight lang="potion">mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)


redblue = "purple"
redblue = "purple"
Line 4,739: Line 4,739:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
An empty hash table can be created with:
An empty hash table can be created with:
<syntaxhighlight lang=powershell>$hashtable = @{}</syntaxhighlight>
<syntaxhighlight lang="powershell">$hashtable = @{}</syntaxhighlight>
A hash table can be initialized with key/value pairs:
A hash table can be initialized with key/value pairs:
<syntaxhighlight lang=powershell>$hashtable = @{
<syntaxhighlight lang="powershell">$hashtable = @{
"key1" = "value 1"
"key1" = "value 1"
key2 = 5 # if the key name has no spaces, no quotes are needed.
key2 = 5 # if the key name has no spaces, no quotes are needed.
}</syntaxhighlight>
}</syntaxhighlight>
Individual values can be assigned or replaced by either using a property-style access method or indexing into the table with the given key:
Individual values can be assigned or replaced by either using a property-style access method or indexing into the table with the given key:
<syntaxhighlight lang=powershell>$hashtable.foo = "bar"
<syntaxhighlight lang="powershell">$hashtable.foo = "bar"
$hashtable['bar'] = 42
$hashtable['bar'] = 42
$hashtable."a b" = 3.14 # keys can contain spaces, property-style access needs quotation marks, then
$hashtable."a b" = 3.14 # keys can contain spaces, property-style access needs quotation marks, then
$hashtable[5] = 8 # keys don't need to be strings</syntaxhighlight>
$hashtable[5] = 8 # keys don't need to be strings</syntaxhighlight>
NB. PowerShell compares strings as case-insensitive, that means the hashtable keys 'a' and 'A' are considered the same key. This happens when @{} is turned into a hashtable, but can be overridden by an explicit long-form:
NB. PowerShell compares strings as case-insensitive, that means the hashtable keys 'a' and 'A' are considered the same key. This happens when @{} is turned into a hashtable, but can be overridden by an explicit long-form:
<syntaxhighlight lang=powershell># Case insensitive keys, both end up as the same key:
<syntaxhighlight lang="powershell"># Case insensitive keys, both end up as the same key:
$h=@{}
$h=@{}
$h['a'] = 1
$h['a'] = 1
Line 4,772: Line 4,772:
a 1 </syntaxhighlight>
a 1 </syntaxhighlight>
Similarly, values can be retrieved using either syntax:
Similarly, values can be retrieved using either syntax:
<syntaxhighlight lang=powershell>$hashtable.key1 # value 1
<syntaxhighlight lang="powershell">$hashtable.key1 # value 1
$hashtable['key2'] # 5</syntaxhighlight>
$hashtable['key2'] # 5</syntaxhighlight>
It is common to see a hashtable literal used to create an object, by casting it to a new type:
It is common to see a hashtable literal used to create an object, by casting it to a new type:
<syntaxhighlight lang=powershell>$obj = [PSCustomObject]@{
<syntaxhighlight lang="powershell">$obj = [PSCustomObject]@{
"key1" = "value 1"
"key1" = "value 1"
key2 = 5
key2 = 5
Line 4,783: Line 4,783:
=={{header|Prolog}}==
=={{header|Prolog}}==
We use the facts table for this purpose.
We use the facts table for this purpose.
<syntaxhighlight lang=prolog>
<syntaxhighlight lang="prolog">
mymap(key1,value1).
mymap(key1,value1).
mymap(key2,value2).
mymap(key2,value2).
Line 4,794: Line 4,794:
Hashes are a built-in type called Map in Purebasic.
Hashes are a built-in type called Map in Purebasic.


<syntaxhighlight lang=purebasic>NewMap dict.s()
<syntaxhighlight lang="purebasic">NewMap dict.s()
dict("country") = "Germany"
dict("country") = "Germany"
Debug dict("country")</syntaxhighlight>
Debug dict("country")</syntaxhighlight>
Line 4,801: Line 4,801:
Hashes are a built-in type called dictionaries (or mappings) in Python.
Hashes are a built-in type called dictionaries (or mappings) in Python.


<syntaxhighlight lang=python>hash = dict() # 'dict' is the dictionary type.
<syntaxhighlight lang="python">hash = dict() # 'dict' is the dictionary type.
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
hash = { 'key1':1, 'key2':2, }
Line 4,808: Line 4,808:
Numerous methods exist for the mapping type https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
Numerous methods exist for the mapping type https://docs.python.org/3/library/stdtypes.html#mapping-types-dict


<syntaxhighlight lang=python># empty dictionary
<syntaxhighlight lang="python"># empty dictionary
d = {}
d = {}
d['spam'] = 1
d['spam'] = 1
Line 4,831: Line 4,831:
Note: Python dictionary keys can be of any arbitrary "hashable" type. The following contains several distinct key value pairs:
Note: Python dictionary keys can be of any arbitrary "hashable" type. The following contains several distinct key value pairs:


<syntaxhighlight lang=python>myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }</syntaxhighlight>
<syntaxhighlight lang="python">myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }</syntaxhighlight>


(Some other languages such as ''awk'' and ''Perl'' evaluate all keys such that numerically or lexically equivalent expressions become identical entries in the hash or associative array).
(Some other languages such as ''awk'' and ''Perl'' evaluate all keys such that numerically or lexically equivalent expressions become identical entries in the hash or associative array).
Line 4,844: Line 4,844:
=== environment example ===
=== environment example ===


<syntaxhighlight lang=r>> env <- new.env()
<syntaxhighlight lang="r">> env <- new.env()
> env[["x"]] <- 123
> env[["x"]] <- 123
> env[["x"]]</syntaxhighlight>
> env[["x"]]</syntaxhighlight>
<pre>[1] 123</pre>
<pre>[1] 123</pre>
<syntaxhighlight lang=r>> index <- "1"
<syntaxhighlight lang="r">> index <- "1"
> env[[index]] <- "rainfed hay"
> env[[index]] <- "rainfed hay"
> env[[index]]</syntaxhighlight>
> env[[index]]</syntaxhighlight>
<pre>[1] "rainfed hay"</pre>
<pre>[1] "rainfed hay"</pre>
<syntaxhighlight lang=r>> env[["1"]]</syntaxhighlight>
<syntaxhighlight lang="r">> env[["1"]]</syntaxhighlight>
<pre>[1] "rainfed hay"</pre>
<pre>[1] "rainfed hay"</pre>
<syntaxhighlight lang=r>> env</syntaxhighlight>
<syntaxhighlight lang="r">> env</syntaxhighlight>
<pre><environment: 0xb7cd560></pre>
<pre><environment: 0xb7cd560></pre>
<syntaxhighlight lang=r>> print(env)</syntaxhighlight>
<syntaxhighlight lang="r">> print(env)</syntaxhighlight>
<pre><environment: 0xb7cd560></pre>
<pre><environment: 0xb7cd560></pre>


=== vector example ===
=== vector example ===


<syntaxhighlight lang=r>> x <- c(hello=1, world=2, "!"=3)
<syntaxhighlight lang="r">> x <- c(hello=1, world=2, "!"=3)
> print(x)</syntaxhighlight>
> print(x)</syntaxhighlight>
<pre>hello world !
<pre>hello world !
1 2 3</pre>
1 2 3</pre>
<syntaxhighlight lang=r>> print(names(x))</syntaxhighlight>
<syntaxhighlight lang="r">> print(names(x))</syntaxhighlight>
<pre>[1] "hello" "world" "!"</pre>
<pre>[1] "hello" "world" "!"</pre>
<syntaxhighlight lang=r>print(unname(x))</syntaxhighlight>
<syntaxhighlight lang="r">print(unname(x))</syntaxhighlight>
<pre>[1] 1 2 3</pre>
<pre>[1] 1 2 3</pre>


=== list example ===
=== list example ===


<syntaxhighlight lang=R>> a <- list(a=1, b=2, c=3.14, d="xyz")
<syntaxhighlight lang="r">> a <- list(a=1, b=2, c=3.14, d="xyz")
> print(a)</syntaxhighlight>
> print(a)</syntaxhighlight>
<pre>$a
<pre>$a
Line 4,885: Line 4,885:
$d
$d
[1] "xyz"</pre>
[1] "xyz"</pre>
<syntaxhighlight lang=r>> print(names(a))</syntaxhighlight>
<syntaxhighlight lang="r">> print(names(a))</syntaxhighlight>
<pre>[1] "a" "b" "c" "d"</pre>
<pre>[1] "a" "b" "c" "d"</pre>
<syntaxhighlight lang=r>> print(unname(a))</syntaxhighlight>
<syntaxhighlight lang="r">> print(unname(a))</syntaxhighlight>
<pre>[[1]]
<pre>[[1]]
[1] 1
[1] 1
Line 4,903: Line 4,903:
In Racket, hash tables are natively supported and encouraged over association lists in many cases. Data structures that behave like dictionaries support a unified interface.
In Racket, hash tables are natively supported and encouraged over association lists in many cases. Data structures that behave like dictionaries support a unified interface.


<syntaxhighlight lang=racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 4,925: Line 4,925:
The fatarrow, <code>=></code>, is no longer just a quoting comma; it now constructs a <code>Pair</code> object. But you can still define a hash with an ordinary list of even length.
The fatarrow, <code>=></code>, is no longer just a quoting comma; it now constructs a <code>Pair</code> object. But you can still define a hash with an ordinary list of even length.


<syntaxhighlight lang=perl6>my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
<syntaxhighlight lang="raku" line>my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';


Line 4,955: Line 4,955:


=={{header|Raven}}==
=={{header|Raven}}==
<syntaxhighlight lang=raven>{ 'a' 1 'b' 2 'c' 3.14 'd' 'xyz' } as a_hash
<syntaxhighlight lang="raven">{ 'a' 1 'b' 2 'c' 3.14 'd' 'xyz' } as a_hash
a_hash print
a_hash print


Line 4,973: Line 4,973:


=={{header|Relation}}==
=={{header|Relation}}==
<syntaxhighlight lang=relation>
<syntaxhighlight lang="relation">
relation key, value
relation key, value
insert "foo", "bar"
insert "foo", "bar"
Line 5,005: Line 5,005:


=={{header|Retro}}==
=={{header|Retro}}==
<syntaxhighlight lang=Retro>with hashTable'
<syntaxhighlight lang="retro">with hashTable'
hashTable constant table
hashTable constant table


Line 5,017: Line 5,017:
===version 1===
===version 1===
Associative arrays are called ''stem variables'' in Rexx.
Associative arrays are called ''stem variables'' in Rexx.
<syntaxhighlight lang=Rexx>/* Rexx */
<syntaxhighlight lang="rexx">/* Rexx */


key0 = '0'
key0 = '0'
Line 5,032: Line 5,032:


===version 2===
===version 2===
<syntaxhighlight lang=rexx>/*REXX program shows how to set/display values for an associative array.*/
<syntaxhighlight lang="rexx">/*REXX program shows how to set/display values for an associative array.*/
/*┌────────────────────────────────────────────────────────────────────┐
/*┌────────────────────────────────────────────────────────────────────┐
│ The (below) two REXX statements aren't really necessary, but it │
│ The (below) two REXX statements aren't really necessary, but it │
Line 5,067: Line 5,067:


=={{header|Ring}}==
=={{header|Ring}}==
<syntaxhighlight lang=ring>
<syntaxhighlight lang="ring">
# Project Associative array/Creation
# Project Associative array/Creation


Line 5,084: Line 5,084:
=={{header|RLaB}}==
=={{header|RLaB}}==
Associative arrays are called ''lists'' in RLaB.
Associative arrays are called ''lists'' in RLaB.
<syntaxhighlight lang=RLaB>
<syntaxhighlight lang="rlab">
x = <<>>; // create an empty list using strings as identifiers.
x = <<>>; // create an empty list using strings as identifiers.
x.red = strtod("0xff0000"); // RLaB doesn't deal with hexadecimal numbers directly. Thus we
x.red = strtod("0xff0000"); // RLaB doesn't deal with hexadecimal numbers directly. Thus we
Line 5,114: Line 5,114:
=={{header|Ruby}}==
=={{header|Ruby}}==
A hash object that returns [[nil]] for unknown keys
A hash object that returns [[nil]] for unknown keys
<syntaxhighlight lang=ruby>hash={}
<syntaxhighlight lang="ruby">hash={}
hash[666]='devil'
hash[666]='devil'
hash[777] # => nil
hash[777] # => nil
Line 5,120: Line 5,120:


A hash object that returns 'unknown key' for unknown keys
A hash object that returns 'unknown key' for unknown keys
<syntaxhighlight lang=ruby>hash=Hash.new('unknown key')
<syntaxhighlight lang="ruby">hash=Hash.new('unknown key')
hash[666]='devil'
hash[666]='devil'
hash[777] # => 'unknown key'
hash[777] # => 'unknown key'
Line 5,126: Line 5,126:


A hash object that returns "unknown key #{key}" for unknown keys
A hash object that returns "unknown key #{key}" for unknown keys
<syntaxhighlight lang=ruby>hash=Hash.new{|h,k| "unknown key #{k}"}
<syntaxhighlight lang="ruby">hash=Hash.new{|h,k| "unknown key #{k}"}
hash[666]='devil'
hash[666]='devil'
hash[777] # => 'unknown key 777'
hash[777] # => 'unknown key 777'
Line 5,132: Line 5,132:


A hash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen
A hash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen
<syntaxhighlight lang=ruby>hash=Hash.new{|h,k|h[k]="key #{k} was added at #{Time.now}"}
<syntaxhighlight lang="ruby">hash=Hash.new{|h,k|h[k]="key #{k} was added at #{Time.now}"}
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'
Line 5,138: Line 5,138:


=={{header|Rust}}==
=={{header|Rust}}==
<syntaxhighlight lang=rust>use std::collections::HashMap;
<syntaxhighlight lang="rust">use std::collections::HashMap;
fn main() {
fn main() {
let mut olympic_medals = HashMap::new();
let mut olympic_medals = HashMap::new();
Line 5,149: Line 5,149:


=={{header|Sather}}==
=={{header|Sather}}==
<syntaxhighlight lang=sather>class MAIN is
<syntaxhighlight lang="sather">class MAIN is
main is
main is
-- creation of a map between strings and integers
-- creation of a map between strings and integers
Line 5,172: Line 5,172:


=={{header|Scala}}==
=={{header|Scala}}==
<syntaxhighlight lang=Scala>// immutable maps
<syntaxhighlight lang="scala">// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map(3) // 4
Line 5,179: Line 5,179:
map.isDefinedAt(44) // true</syntaxhighlight>
map.isDefinedAt(44) // true</syntaxhighlight>


<syntaxhighlight lang=scala>// mutable maps (HashSets)
<syntaxhighlight lang="scala">// mutable maps (HashSets)
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashMap
val hash = new HashMap[Int, Int]
val hash = new HashMap[Int, Int]
Line 5,190: Line 5,190:
hash.contains(44) // true</syntaxhighlight>
hash.contains(44) // true</syntaxhighlight>


<syntaxhighlight lang=scala>// iterate over key/value
<syntaxhighlight lang="scala">// iterate over key/value
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
// same with for syntax
// same with for syntax
for((k,v) <- hash) println("key " + k + " value " + v)</syntaxhighlight>
for((k,v) <- hash) println("key " + k + " value " + v)</syntaxhighlight>


<syntaxhighlight lang=scala>// items in map where the key is greater than 3
<syntaxhighlight lang="scala">// items in map where the key is greater than 3
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
// same with for syntax
// same with for syntax
Line 5,203: Line 5,203:


Scheme has association lists (alists), which are inefficient, ordered maps with arbitrary keys and values.
Scheme has association lists (alists), which are inefficient, ordered maps with arbitrary keys and values.
<syntaxhighlight lang=scheme>(define my-dict '((a b) (1 hello) ("c" (a b c)))
<syntaxhighlight lang="scheme">(define my-dict '((a b) (1 hello) ("c" (a b c)))
(assoc 'a my-dict) ; evaluates to '(a b)</syntaxhighlight>
(assoc 'a my-dict) ; evaluates to '(a b)</syntaxhighlight>


Line 5,209: Line 5,209:
Hash tables are provided by SRFI-69 [http://srfi.schemers.org/srfi-69/srfi-69.html]. Many Scheme implementation also provide native hash tables.
Hash tables are provided by SRFI-69 [http://srfi.schemers.org/srfi-69/srfi-69.html]. Many Scheme implementation also provide native hash tables.


<syntaxhighlight lang=scheme>(define my-alist '((a b) (1 hello) ("c" (a b c)))
<syntaxhighlight lang="scheme">(define my-alist '((a b) (1 hello) ("c" (a b c)))
(define my-hash (alist->hash-table my-alist))</syntaxhighlight>
(define my-hash (alist->hash-table my-alist))</syntaxhighlight>


The R6RS standard specifies support for hashtables in the [http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-14.html#node_chap_13 standard libraries] document.
The R6RS standard specifies support for hashtables in the [http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-14.html#node_chap_13 standard libraries] document.


<syntaxhighlight lang=scheme>#!r6rs
<syntaxhighlight lang="scheme">#!r6rs


(import (rnrs base)
(import (rnrs base)
Line 5,236: Line 5,236:
Associate arrays are not part of the Scheme language itself, but are compiler/interpreter or library add-ons. So I feel justified in presenting this sketch of yet another library add-on.
Associate arrays are not part of the Scheme language itself, but are compiler/interpreter or library add-ons. So I feel justified in presenting this sketch of yet another library add-on.


<syntaxhighlight lang=scheme>(cond-expand
<syntaxhighlight lang="scheme">(cond-expand
(r7rs)
(r7rs)
(chicken (import r7rs)))
(chicken (import r7rs)))
Line 5,642: Line 5,642:
Seed7 uses the type [http://seed7.sourceforge.net/manual/types.htm#hash hash] to support associative arrays.
Seed7 uses the type [http://seed7.sourceforge.net/manual/types.htm#hash hash] to support associative arrays.


<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


# Define hash type
# Define hash type
Line 5,690: Line 5,690:
=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
Associative arrays in SenseTalk are called property lists, or objects.
Associative arrays in SenseTalk are called property lists, or objects.
<syntaxhighlight lang=sensetalk>put {} into emptyPlist
<syntaxhighlight lang="sensetalk">put {} into emptyPlist
put an empty property list into emptyPlist2
put an empty property list into emptyPlist2


Line 5,706: Line 5,706:
=={{header|SETL}}==
=={{header|SETL}}==
Associative arrays (referred to in SETL terminology as <i>maps</i>) are implemented as sets whose only members are tuples of length 2. Create such a set:
Associative arrays (referred to in SETL terminology as <i>maps</i>) are implemented as sets whose only members are tuples of length 2. Create such a set:
<syntaxhighlight lang=setl>m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};</syntaxhighlight>
<syntaxhighlight lang="setl">m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};</syntaxhighlight>
We can then index the set, or map, with the first element of a constituent tuple to return that tuple's second element:
We can then index the set, or map, with the first element of a constituent tuple to return that tuple's second element:
<syntaxhighlight lang=setl>print( m('bar') );</syntaxhighlight>
<syntaxhighlight lang="setl">print( m('bar') );</syntaxhighlight>
{{out}}
{{out}}
<pre>b</pre>
<pre>b</pre>
If the map might contain more than one value associated with the same key, we can return the set of them (in this instance a unit set because the keys are in fact unique):
If the map might contain more than one value associated with the same key, we can return the set of them (in this instance a unit set because the keys are in fact unique):
<syntaxhighlight lang=setl>print( m{'bar'} );</syntaxhighlight>
<syntaxhighlight lang="setl">print( m{'bar'} );</syntaxhighlight>
{{out}}
{{out}}
<pre>{b}</pre>
<pre>{b}</pre>


=={{header|SETL4}}==
=={{header|SETL4}}==
<syntaxhighlight lang=Setl4>
<syntaxhighlight lang="setl4">
* Iterate over key-value pairs of a map
* Iterate over key-value pairs of a map


Line 5,745: Line 5,745:


=={{header|Sidef}}==
=={{header|Sidef}}==
<syntaxhighlight lang=ruby>var hash = Hash.new(
<syntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key1 => 'value1',
key2 => 'value2',
key2 => 'value2',
Line 5,755: Line 5,755:
=={{header|Slate}}==
=={{header|Slate}}==
<syntaxhighlight lang=slate>Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</syntaxhighlight>
<syntaxhighlight lang="slate">Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<syntaxhighlight lang=smalltalk>states := Dictionary new.
<syntaxhighlight lang="smalltalk">states := Dictionary new.
states at: 'MI' put: 'Michigan'.
states at: 'MI' put: 'Michigan'.
states at: 'MN' put: 'Minnesota'.</syntaxhighlight>
states at: 'MN' put: 'Minnesota'.</syntaxhighlight>
alternative:
alternative:
<syntaxhighlight lang=smalltalk>Dictionary withAssociations:{ 'MI' -> 'Michigan' . 'MN' -> 'Minnesota'}</syntaxhighlight>
<syntaxhighlight lang="smalltalk">Dictionary withAssociations:{ 'MI' -> 'Michigan' . 'MN' -> 'Minnesota'}</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<syntaxhighlight lang=snobol4> t = table()
<syntaxhighlight lang="snobol4"> t = table()
t<"red"> = "#ff0000"
t<"red"> = "#ff0000"
t<"green"> = "#00ff00"
t<"green"> = "#00ff00"
Line 5,776: Line 5,776:


=={{header|SQL}}==
=={{header|SQL}}==
<syntaxhighlight lang=SQL>
<syntaxhighlight lang="sql">
REM Create a table to associate keys with values
REM Create a table to associate keys with values
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
Line 5,788: Line 5,788:
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<syntaxhighlight lang=sql pl>
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
--#SET TERMINATOR @


Line 5,827: Line 5,827:


=={{header|Stata}}==
=={{header|Stata}}==
<syntaxhighlight lang=stata>mata
<syntaxhighlight lang="stata">mata
a=asarray_create()
a=asarray_create()


Line 5,847: Line 5,847:


=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang=swift>// make an empty map
<syntaxhighlight lang="swift">// make an empty map
var a = [String: Int]()
var a = [String: Int]()
// or
// or
Line 5,863: Line 5,863:
=={{header|Symsyn}}==
=={{header|Symsyn}}==
Symsyn implements Hash as a list of strings. Each name/value or key/value pair is stored in another string. The name/value pair is in the format 'name=value', the '=' is reserved.
Symsyn implements Hash as a list of strings. Each name/value or key/value pair is stored in another string. The name/value pair is in the format 'name=value', the '=' is reserved.
<syntaxhighlight lang=Symsyn>
<syntaxhighlight lang="symsyn">
#+ 'name=bob' $hash | add to hash
#+ 'name=bob' $hash | add to hash
#? 'name' $hash $S | find 'name' and return 'bob' in $S
#? 'name' $hash $S | find 'name' and return 'bob' in $S
Line 5,871: Line 5,871:
All arrays in Tcl are associative.
All arrays in Tcl are associative.


<syntaxhighlight lang=tcl># Create one element at a time:
<syntaxhighlight lang="tcl"># Create one element at a time:
set hash(foo) 5
set hash(foo) 5


Line 5,892: Line 5,892:
<br>
<br>
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<syntaxhighlight lang=tcl># Create in bulk
<syntaxhighlight lang="tcl"># Create in bulk
set d [dict create foo 5 bar 10 baz 15]
set d [dict create foo 5 bar 10 baz 15]


Line 5,916: Line 5,916:
Toka provides associative arrays via a library.
Toka provides associative arrays via a library.


<syntaxhighlight lang=toka>needs asarray
<syntaxhighlight lang="toka">needs asarray


( create an associative array )
( create an associative array )
Line 5,933: Line 5,933:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|ksh}}
{{works with|ksh}}
<syntaxhighlight lang=bash>typeset -A hash
<syntaxhighlight lang="bash">typeset -A hash
hash=( [key1]=val1 [key2]=val2 )
hash=( [key1]=val1 [key2]=val2 )
hash[key3]=val3
hash[key3]=val3
Line 5,940: Line 5,940:
{{works with|bash}}
{{works with|bash}}
assigning values is the same as ksh, but to declare the variable as an associative array:
assigning values is the same as ksh, but to declare the variable as an associative array:
<syntaxhighlight lang=bash>declare -A hash</syntaxhighlight>
<syntaxhighlight lang="bash">declare -A hash</syntaxhighlight>


=={{header|UnixPipes}}==
=={{header|UnixPipes}}==
A key value file can be considered as an associative array
A key value file can be considered as an associative array
<syntaxhighlight lang=bash>map='p.map'
<syntaxhighlight lang="bash">map='p.map'


function init() {
function init() {
Line 5,991: Line 5,991:
=={{header|Vala}}==
=={{header|Vala}}==
{{libheader|Gee}}
{{libheader|Gee}}
<syntaxhighlight lang=vala>
<syntaxhighlight lang="vala">
using Gee;
using Gee;


Line 6,016: Line 6,016:
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.


<syntaxhighlight lang=vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
Sub Test()
Sub Test()
Dim h As Object
Dim h As Object
Line 6,035: Line 6,035:
=={{header|Vim Script}}==
=={{header|Vim Script}}==
Dictionary keys are always strings.
Dictionary keys are always strings.
<syntaxhighlight lang=vim>" Creating a dictionary with some initial values
<syntaxhighlight lang="vim">" Creating a dictionary with some initial values
let dict = {"one": 1, "two": 2}
let dict = {"one": 1, "two": 2}


Line 6,058: Line 6,058:
=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
Visual FoxPro has a collection class which can be used for this.
Visual FoxPro has a collection class which can be used for this.
<syntaxhighlight lang=vfp>
<syntaxhighlight lang="vfp">
LOCAL loCol As Collection, k, n, o
LOCAL loCol As Collection, k, n, o
CLEAR
CLEAR
Line 6,101: Line 6,101:


=={{header|Vlang}}==
=={{header|Vlang}}==
<syntaxhighlight lang=vlang>fn main() {
<syntaxhighlight lang="vlang">fn main() {
// make empty map
// make empty map
mut my_map := map[string]int{}
mut my_map := map[string]int{}
Line 6,123: Line 6,123:


=={{header|Wart}}==
=={{header|Wart}}==
<syntaxhighlight lang=wart>h <- (table 'a 1 'b 2)
<syntaxhighlight lang="wart">h <- (table 'a 1 'b 2)
h 'a
h 'a
=> 1</syntaxhighlight>
=> 1</syntaxhighlight>
Line 6,129: Line 6,129:
=={{header|Wren}}==
=={{header|Wren}}==
Wren has a Map class built in.
Wren has a Map class built in.
<syntaxhighlight lang=ecmascript>var fruit = {} // creates an empty map
<syntaxhighlight lang="ecmascript">var fruit = {} // creates an empty map
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[2] = "apple" // associates a key of 2 with "apple"
fruit[2] = "apple" // associates a key of 2 with "apple"
Line 6,162: Line 6,162:
=={{header|XLISP}}==
=={{header|XLISP}}==
XLISP refers to associative arrays as tables. The <tt>MAKE-TABLE</tt> function returns a new empty table, for instance:
XLISP refers to associative arrays as tables. The <tt>MAKE-TABLE</tt> function returns a new empty table, for instance:
<syntaxhighlight lang=lisp>(define starlings (make-table))</syntaxhighlight>
<syntaxhighlight lang="lisp">(define starlings (make-table))</syntaxhighlight>
Values can then be inserted using <tt>TABLE-SET!</tt>:
Values can then be inserted using <tt>TABLE-SET!</tt>:
<syntaxhighlight lang=lisp>(table-set! starlings "Common starling" "Sturnus vulgaris")
<syntaxhighlight lang="lisp">(table-set! starlings "Common starling" "Sturnus vulgaris")
(table-set! starlings "Abbot's starling" "Poeoptera femoralis")
(table-set! starlings "Abbot's starling" "Poeoptera femoralis")
(table-set! starlings "Cape starling" "Lamprotornis nitens")</syntaxhighlight>
(table-set! starlings "Cape starling" "Lamprotornis nitens")</syntaxhighlight>
and retrieved using <tt>TABLE-REF</tt> with their keys:
and retrieved using <tt>TABLE-REF</tt> with their keys:
<syntaxhighlight lang=lisp>(table-ref starlings "Cape starling")</syntaxhighlight>
<syntaxhighlight lang="lisp">(table-ref starlings "Cape starling")</syntaxhighlight>
Output in a REPL:
Output in a REPL:
<pre>"Lamprotornis nitens"</pre>
<pre>"Lamprotornis nitens"</pre>
Other functions provided for tables include <tt>MAP-OVER-TABLE-ENTRIES</tt>, which takes a table and a function of two arguments and applies the function to each entry (using the key and value as the two arguments), for instance:
Other functions provided for tables include <tt>MAP-OVER-TABLE-ENTRIES</tt>, which takes a table and a function of two arguments and applies the function to each entry (using the key and value as the two arguments), for instance:
<syntaxhighlight lang=lisp>(map-over-table-entries starlings (lambda (x y) (print (string-append x " (Linnaean name " y ")"))))</syntaxhighlight>
<syntaxhighlight lang="lisp">(map-over-table-entries starlings (lambda (x y) (print (string-append x " (Linnaean name " y ")"))))</syntaxhighlight>
Output in a REPL:
Output in a REPL:
<pre>"Abbott's starling (Linnaean name Poeoptera femoralis)"
<pre>"Abbott's starling (Linnaean name Poeoptera femoralis)"
Line 6,179: Line 6,179:


=={{header|XPL0}}==
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0>include c:\cxpl\stdlib;
<syntaxhighlight lang="xpl0">include c:\cxpl\stdlib;
char Dict(10,10);
char Dict(10,10);
int Entries;
int Entries;
Line 6,218: Line 6,218:


=={{header|zkl}}==
=={{header|zkl}}==
<syntaxhighlight lang=zkl>zkl: Dictionary("one",1, "two",2, "three",3)
<syntaxhighlight lang="zkl">zkl: Dictionary("one",1, "two",2, "three",3)
D(two:2,three:3,one:1)
D(two:2,three:3,one:1)