Associative array/Creation: Difference between revisions

Content added Content deleted
(Added 4tH example)
m (syntax highlighting fixup automation)
Line 14: Line 14:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>V dict = [‘key1’ = 1, ‘key2’ = 2]
<syntaxhighlight lang=11l>V dict = [‘key1’ = 1, ‘key2’ = 2]
V value2 = dict[‘key2’]</lang>
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:
<lang Forth>
<syntaxhighlight lang=Forth>
{ "one" : 1, "two" : "bad" }
{ "one" : 1, "two" : "bad" }
</syntaxhighlight>
</lang>
Alternatively, they can be created in code:
Alternatively, they can be created in code:
<lang Forth>
<syntaxhighlight lang=Forth>
m:new "one" 1 m:! "two" "bad" m:!
m:new "one" 1 m:! "two" "bad" m:!
</syntaxhighlight>
</lang>
=={{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 }}
<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 425: Line 425:
.include "../includeARM64.inc"
.include "../includeARM64.inc"


</syntaxhighlight>
</lang>


=={{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.
<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 437: Line 437:
// More keys and values can then be added
// More keys and values can then be added
map['key3'] = "value3";
map['key3'] = "value3";
trace(map['key3']); // outputs "value3"</lang>
trace(map['key3']); // outputs "value3"</syntaxhighlight>
''Note: The Object only supports String keys. To use an object as a key, try the flash.utils.Dictionary class.''
''Note: The Object only supports String keys. To use an object as a key, try the flash.utils.Dictionary class.''


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
{{works with|GNAT|GPL 2007}}
<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 474: Line 474:
Value := Color_Map.Element(To_Unbounded_String("Yellow"));
Value := Color_Map.Element(To_Unbounded_String("Yellow"));
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value));
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value));
end Associative_Array;</lang>
end Associative_Array;</syntaxhighlight>


=={{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.
<lang aikido>
<syntaxhighlight lang=aikido>
var names = {} // empty map
var names = {} // empty map
names["foo"] = "bar"
names["foo"] = "bar"
Line 498: Line 498:




</syntaxhighlight>
</lang>


=={{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.
<lang aime>record r;</lang>
<syntaxhighlight lang=aime>record r;</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</lang>
r_put(r, "B", "associative"); # a string value</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
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}}
<lang algol68>main:(
<syntaxhighlight lang=algol68>main:(


MODE COLOR = BITS;
MODE COLOR = BITS;
Line 583: Line 583:
printf(($g$,"values: ", comma sep, value OF color map items, $l$))
printf(($g$,"values: ", comma sep, value OF color map items, $l$))


)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 600: Line 600:


Creating a new empty map of String to String:
Creating a new empty map of String to String:
<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 608: Line 608:
System.assertEquals( 'bval', strMap.get('b') );
System.assertEquals( 'bval', strMap.get('b') );
// String keys are case-sensitive
// String keys are case-sensitive
System.assert( !strMap.containsKey('A') );</lang>
System.assert( !strMap.containsKey('A') );</syntaxhighlight>


Creating a new map of String to String with values initialized:
Creating a new map of String to String with values initialized:
<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 617: Line 617:


System.assert( strMap.containsKey('a') );
System.assert( strMap.containsKey('a') );
System.assertEquals( 'bval', strMap.get('b') );</lang>
System.assertEquals( 'bval', strMap.get('b') );</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<lang apl>⍝ Create a namespace ("hash")
<syntaxhighlight lang=apl>⍝ Create a namespace ("hash")
X←⎕NS ⍬
X←⎕NS ⍬
Line 642: Line 642:
sales.revenue
sales.revenue
4109.6
4109.6
</syntaxhighlight>
</lang>


{{works with|GNU APL}}
{{works with|GNU APL}}
<lang apl>
<syntaxhighlight lang=apl>
⍝ Assign some names
⍝ Assign some names
X.this←'that'
X.this←'that'
Line 672: Line 672:
sales.revenue
sales.revenue
4109.6
4109.6
</syntaxhighlight>
</lang>


=={{header|App Inventor}}==
=={{header|App Inventor}}==
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}}
<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,054: Line 1,054:
.include "../affichage.inc"
.include "../affichage.inc"


</syntaxhighlight>
</lang>
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>; create a dictionary
<syntaxhighlight lang=rebol>; create a dictionary
d: #[
d: #[
name: "john"
name: "john"
Line 1,064: Line 1,064:
]
]


print d</lang>
print d</syntaxhighlight>


{{out}}
{{out}}
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.
<lang ATS>(*------------------------------------------------------------------*)
<syntaxhighlight lang=ATS>(*------------------------------------------------------------------*)


#define ATS_DYNLOADFLAG 0
#define ATS_DYNLOADFLAG 0
Line 1,303: Line 1,303:
end
end


(*------------------------------------------------------------------*)</lang>
(*------------------------------------------------------------------*)</syntaxhighlight>


{{out}}
{{out}}
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.


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


#define ATS_DYNLOADFLAG 0
#define ATS_DYNLOADFLAG 0
Line 1,902: Line 1,902:
end
end


(*------------------------------------------------------------------*)</lang>
(*------------------------------------------------------------------*)</syntaxhighlight>


{{out}}
{{out}}
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.
<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 !*+"]</lang>
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</syntaxhighlight>
=== Legacy versions ===
=== Legacy versions ===
[[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.
<lang AutoHotkey>arrayX1 = first
<syntaxhighlight lang=AutoHotkey>arrayX1 = first
arrayX2 = second
arrayX2 = second
arrayX3 = foo
arrayX3 = foo
arrayX4 = bar
arrayX4 = bar
Loop, 4
Loop, 4
Msgbox % arrayX%A_Index%</lang>
Msgbox % arrayX%A_Index%</syntaxhighlight>


=={{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.
<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,059: Line 2,059:


;; End AA Functions.
;; End AA Functions.
</syntaxhighlight>
</lang>


=={{header|AWK}}==
=={{header|AWK}}==
Arrays in AWK are indeed associative arrays.
Arrays in AWK are indeed associative arrays.
<lang awk>BEGIN {
<syntaxhighlight lang=awk>BEGIN {
a["red"] = 0xff0000
a["red"] = 0xff0000
a["green"] = 0x00ff00
a["green"] = 0x00ff00
Line 2,078: Line 2,078:
print ( "red" in a ) # print 0
print ( "red" in a ) # print 0
print ( "blue" in a ) # print 1
print ( "blue" in a ) # print 1
}</lang>
}</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==


<lang babel>
<syntaxhighlight lang=babel>
(("foo" 13)
(("foo" 13)
("bar" 42)
("bar" 42)
("baz" 77)) ls2map !</lang>
("baz" 77)) ls2map !</syntaxhighlight>


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


associative("abc") = "first three"
associative("abc") = "first three"
associative("xyz") = "last three"
associative("xyz") = "last three"


PRINT associative("xyz")</lang>
PRINT associative("xyz")</syntaxhighlight>


{{out}}
{{out}}
Line 2,103: Line 2,103:


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<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,208: Line 2,208:
next n
next n
return ""
return ""
end function</lang>
end function</syntaxhighlight>
{{out}}
{{out}}
<pre>a apple
<pre>a apple
Line 2,222: Line 2,222:
This is cheating, I'm sure of it.
This is cheating, I'm sure of it.


<lang dos>::assocarrays.cmd
<syntaxhighlight lang=dos>::assocarrays.cmd
@echo off
@echo off
setlocal ENABLEDELAYEDEXPANSION
setlocal ENABLEDELAYEDEXPANSION
Line 2,246: Line 2,246:
echo %1 = %2
echo %1 = %2
goto :eof
goto :eof
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,259: Line 2,259:


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<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,279: Line 2,279:
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</lang>
= MID$(dict$, I%, J% - I%)</syntaxhighlight>


=={{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.
<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,292: Line 2,292:
& (myhash..remove)$formula
& (myhash..remove)$formula
& (myhash..insert)$(formula.x^2+y^2)
& (myhash..insert)$(formula.x^2+y^2)
& out$(myhash..find)$formula;</lang>
& out$(myhash..find)$formula;</syntaxhighlight>
{{out}}
{{out}}
<pre>(fruit.melons bananas) (fruit.apples oranges kiwis)
<pre>(fruit.melons bananas) (fruit.apples oranges kiwis)
Line 2,298: Line 2,298:


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


h[:a] = 1 #Assign value
h[:a] = 1 #Assign value
Line 2,305: Line 2,305:
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash


h2[:b][2] #Returns 3</lang>
h2[:b][2] #Returns 3</syntaxhighlight>


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


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


{{works with|C sharp|C#|3.0+}}
{{works with|C sharp|C#|3.0+}}
<lang csharp>var map = new Dictionary<string, string> {{"key1", "foo"}};</lang>
<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'''.


<lang cpp>#include <map></lang>
<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:
<lang cpp>std::map<A, B> exampleMap</lang>
<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:


<lang cpp>std::map<int, double> exampleMap</lang>
<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.
<lang cpp>exampleMap[7] = 3.14</lang>
<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:
<lang cpp>int myKey = 7;
<syntaxhighlight lang=cpp>int myKey = 7;
double myValue = 3.14;
double myValue = 3.14;
exampleMap[myKey] = myValue;</lang>
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:
<lang cpp>exampleMap.insert(std::pair<int, double>(7,3.14));</lang>
<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:
<lang cpp>exampleMap.insert(std::make_pair(7,3.14));</lang>
<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:
<lang cpp>myValue = exampleMap[myKey]</lang>
<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]]:
<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,366: Line 2,366:
// Return the value for that key.
// Return the value for that key.
myValue = myIterator->second;
myValue = myIterator->second;
}</lang>
}</syntaxhighlight>


The need for the '''->second''' code is because our iterator points to a '''pair<>()''', and our value is the second member of that pair.
The need for the '''->second''' code is because our iterator points to a '''pair<>()''', and our value is the second member of that pair.
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.
<lang cpp>#include <map>
<syntaxhighlight lang=cpp>#include <map>
#include <iostreams>
#include <iostreams>


Line 2,399: Line 2,399:
// main() must return 0 on success.
// main() must return 0 on success.
return 0;
return 0;
}</lang>
}</syntaxhighlight>


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


ArrayList,
ArrayList,
Line 2,437: Line 2,437:
}
}
}</lang>
}</syntaxhighlight>


=={{header|Chapel}}==
=={{header|Chapel}}==
Line 2,472: Line 2,472:


writeln("arr2 keys: ", arr2.domain);
writeln("arr2 keys: ", arr2.domain);
writeln("arr2 values: ", arr2);</lang>
writeln("arr2 values: ", arr2);</syntaxhighlight>


{{out}}
{{out}}
Line 2,483: Line 2,483:


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


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<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">
<cfset myHash.put("key3","java-style")></lang>
<cfset myHash.put("key3","java-style")></syntaxhighlight>


In ColdFusion, a map is literally a java.util.HashMap, thus the above 3rd method is possible.
In ColdFusion, a map is literally a java.util.HashMap, thus the above 3rd method is possible.


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<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,508: Line 2,508:
;; alist is written like this:
;; alist is written like this:
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</lang>
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
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/>
<lang oberon2>
<syntaxhighlight lang=oberon2>
DEFINITION Collections;
DEFINITION Collections;


Line 2,581: Line 2,581:


END Collections.
END Collections.
</syntaxhighlight>
</lang>
The program:
The program:
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE BbtAssociativeArrays;
MODULE BbtAssociativeArrays;
IMPORT StdLog, Collections, Boxes;
IMPORT StdLog, Collections, Boxes;
Line 2,606: Line 2,606:


END BbtAssociativeArrays.
END BbtAssociativeArrays.
</syntaxhighlight>
</lang>
Execute:^Q BbtAssociativeArrays.Do<br/>
Execute:^Q BbtAssociativeArrays.Do<br/>
{{out}}
{{out}}
Line 2,614: Line 2,614:


=={{header|Crystal}}==
=={{header|Crystal}}==
<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
# the following would fail without `of String => String|Int32`
# the following would fail without `of String => String|Int32`
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32</lang>
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<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);
}</lang>
}</syntaxhighlight>


=={{header|Dao}}==
=={{header|Dao}}==
<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


m = { 'foo' => 42, 'bar' => 100 } # with ordered keys
m = { 'foo' => 42, 'bar' => 100 } # with ordered keys
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys</lang>
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<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,670: Line 2,670:
}
}


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,687: Line 2,687:


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


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 2,705: Line 2,705:
lDictionary.Free;
lDictionary.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Diego}}==
=={{header|Diego}}==
Line 2,711: Line 2,711:


To create a dictionary associative array:
To create a dictionary associative array:
<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);


reset_ns[];</lang>
reset_ns[];</syntaxhighlight>


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


add_hash(tanzanianBanknoteReverseDipiction)_values(
add_hash(tanzanianBanknoteReverseDipiction)_values(
Line 2,728: Line 2,728:
);
);


reset_ns[];</lang>
reset_ns[];</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
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:


<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())</lang>
print(t.Keys().ToArray())</syntaxhighlight>


{{out}}
{{out}}
Line 2,742: Line 2,742:


=={{header|E}}==
=={{header|E}}==
<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
["one" => 2].diverge(String, float64) # mutable, initial contents,
["one" => 2].diverge(String, float64) # mutable, initial contents,
# typed (coerces to float)</lang>
# typed (coerces to float)</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<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,768: Line 2,768:
(hash-count H)
(hash-count H)
→ 3
→ 3
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0:
ELENA 5.0:
<lang elena>import system'collections;
<syntaxhighlight lang=elena>import system'collections;
public program()
public program()
Line 2,783: Line 2,783:
map["key3"]:= "foo3";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
map["key4"]:= "foo4";
}</lang>
}</syntaxhighlight>


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


public program()
public program()
Line 2,797: Line 2,797:
map["key3"]:= "foo3";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
map["key4"]:= "foo4";
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
{{trans|Erlang}}
{{trans|Erlang}}
<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,817: Line 2,817:
end
end


RC.test_create</lang>
RC.test_create</syntaxhighlight>


{{out}}
{{out}}
Line 2,831: Line 2,831:


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(setq my-table (make-hash-table))
<syntaxhighlight lang=Lisp>(setq my-table (make-hash-table))
(puthash 'key 'value my-table)</lang>
(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,


<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)</lang>
(puthash "key" 123 my-table)</syntaxhighlight>


<code>define-hash-table-test</code> can create other key comparison types.
<code>define-hash-table-test</code> can create other key comparison types.
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.
<lang erlang>
<syntaxhighlight lang=erlang>
-module(assoc).
-module(assoc).
-compile([export_all]).
-compile([export_all]).
Line 2,858: Line 2,858:
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
end, dict:fetch_keys(D)).
end, dict:fetch_keys(D)).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
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)
<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") ;
dic.["key"] <- "new val" ;
dic.["key"] <- "new val" ;
</syntaxhighlight>
</lang>
Functional dictionary (immutable)
Functional dictionary (immutable)
<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,884: Line 2,884:
| Some(v) -> printfn "%s" v
| Some(v) -> printfn "%s" v
| None -> printfn "not found"
| None -> printfn "not found"
</syntaxhighlight>
</lang>


=={{header|Factor}}==
=={{header|Factor}}==
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 :
<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 . ]
[ "three" swap at . ]
[ "three" swap at . ]
[ [ 3 "three" ] dip set-at ]
[ [ 3 "three" ] dip set-at ]
[ "three" swap at . ] } cleave</lang>
[ "three" swap at . ] } cleave</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 2,900: Line 2,900:
Associative arrays are called 'maps' in Fantom:
Associative arrays are called 'maps' in Fantom:


<lang fantom>
<syntaxhighlight lang=fantom>
class Main
class Main
{
{
Line 2,918: Line 2,918:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
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.


<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,945: Line 2,945:
s" alpha" bar get . \ 5
s" alpha" bar get . \ 5
8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive
8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive
s" alpha" bar get . \ 8</lang>
s" alpha" bar get . \ 8</syntaxhighlight>
This is not necessarily a good option in all Forths, as the dictionary may be implemented as a simple linked list (normally not a problem because the dictionary is only used for compiling and interactive interpretation). [[GNU Forth]] and many other hosted Forths use hash tables for the dictionary, so this is a fine choice. If you need case-sensitive keys, GNU Forth has <tt>table</tt> and <tt>table-find</tt>, replacing <tt>wordlist</tt> and <tt>search-wordlist</tt>, respectively.
This is not necessarily a good option in all Forths, as the dictionary may be implemented as a simple linked list (normally not a problem because the dictionary is only used for compiling and interactive interpretation). [[GNU Forth]] and many other hosted Forths use hash tables for the dictionary, so this is a fine choice. If you need case-sensitive keys, GNU Forth has <tt>table</tt> and <tt>table-find</tt>, replacing <tt>wordlist</tt> and <tt>search-wordlist</tt>, respectively.


Line 2,953: Line 2,953:


Hashtable for mapping strings to integer
Hashtable for mapping strings to integer
<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,971: Line 2,971:
[ELSE]
[ELSE]
.( Entry not present.) cr
.( Entry not present.) cr
[THEN]</lang>
[THEN]</syntaxhighlight>
{{works with|4tH|3.64}}
{{works with|4tH|3.64}}


Line 2,998: Line 2,998:
.( Value: ) . cr
.( Value: ) . cr
then
then
</syntaxhighlight>
</lang>


=={{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.
<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,070: Line 3,070:


print Dictionary(0).value.value.strng
print Dictionary(0).value.value.strng
print Dictionary(1).key.value.integ</lang>
print Dictionary(1).key.value.integ</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
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.
<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,095: Line 3,095:
lDictionary.Free;
lDictionary.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>
FPC 2.4+. Using FGL instead of rtl-generics:
FPC 2.4+. Using FGL instead of rtl-generics:
<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,113: Line 3,113:
lDictionary.Free;
lDictionary.Free;
end;
end;
end.</lang>
end.</syntaxhighlight>


=={{header|Futhark}}==
=={{header|Futhark}}==
<lang futhark>let associative_array = {key1=1,key2=2}</lang>
<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.
<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,145: Line 3,145:
x = map[string]int{
x = map[string]int{
"foo": 2, "bar": 42, "baz": -1,
"foo": 2, "bar": 42, "baz": -1,
}</lang>
}</syntaxhighlight>


=={{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.
<lang javascript>// empty map
<syntaxhighlight lang=javascript>// empty map
var emptyMap = new HashMap<String, Integer>()
var emptyMap = new HashMap<String, Integer>()


Line 3,183: Line 3,183:
var scott = new Person()
var scott = new Person()
scott["name"] = "Scott"
scott["name"] = "Scott"
scott["age"] = 29</lang>
scott["age"] = 29</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Create an empty map and add values
Create an empty map and add values
<lang groovy>map = [:]
<syntaxhighlight lang=groovy>map = [:]
map[7] = 7
map[7] = 7
map['foo'] = 'foovalue'
map['foo'] = 'foovalue'
Line 3,196: Line 3,196:
assert 'foovalue' == map.foo
assert 'foovalue' == map.foo
assert 'barvalue' == map['bar']
assert 'barvalue' == map['bar']
assert 'moovalue' == map.get('moo')</lang>
assert 'moovalue' == map.get('moo')</syntaxhighlight>


Create a pre-populated map and verify values
Create a pre-populated map and verify values
<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]
assert 'foovalue' == map.foo
assert 'foovalue' == map.foo
assert 'barvalue' == map['bar']
assert 'barvalue' == map['bar']
assert 'moovalue' == map.get('moo')</lang>
assert 'moovalue' == map.get('moo')</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
Create an empty array and add values:
Create an empty array and add values:
<lang visualfoxpro>arr := { => }
<syntaxhighlight lang=visualfoxpro>arr := { => }
arr[ 10 ] := "Val_10"
arr[ 10 ] := "Val_10"
arr[ "foo" ] := "foovalue"</lang>
arr[ "foo" ] := "foovalue"</syntaxhighlight>
Create and initialize array:
Create and initialize array:
<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" }</lang>
arr := { 10 => "Val_10", "foo" => "foovalue" }</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Binary trees:
Binary trees:
{{works with|GHC}}
{{works with|GHC}}
<lang haskell>import Data.Map
<syntaxhighlight lang=haskell>import Data.Map


dict = fromList [("key1","val1"), ("key2","val2")]
dict = fromList [("key1","val1"), ("key2","val2")]


ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2"
ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2"
</syntaxhighlight>
</lang>


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.
<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"
</syntaxhighlight>
</lang>


GHC also had an imperative hash table implementation in the <code>Data.HashTable</code> module, but was removed in <code>GHC 7.8</code>.
GHC also had an imperative hash table implementation in the <code>Data.HashTable</code> module, but was removed in <code>GHC 7.8</code>.
Line 3,237: Line 3,237:


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<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


println d["test"]
println d["test"]
println d[123]</lang>
println d[123]</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
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.


<lang icon>procedure main()
<syntaxhighlight lang=icon>procedure main()
local t
local t
t := table()
t := table()
t["foo"] := "bar"
t["foo"] := "bar"
write(t["foo"])
write(t["foo"])
end</lang>
end</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
Line 3,258: Line 3,258:


===Static relation===
===Static relation===
<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,275: Line 3,275:
let V be the number that "baz" relates to by the connection relation;
let V be the number that "baz" relates to by the connection relation;
say "'baz' => [V].";
say "'baz' => [V].";
end the story.</lang>
end the story.</syntaxhighlight>


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


When play begins:
When play begins:
Line 3,292: Line 3,292:
let V be the number that "baz" relates to by R;
let V be the number that "baz" relates to by R;
say "'baz' => [V].";
say "'baz' => [V].";
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|Ioke}}==
=={{header|Ioke}}==
<lang ioke>{a: "a", b: "b"}</lang>
<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):


<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
has=: 0 <: nc@<@encode
has=: 0 <: nc@<@encode
set=:4 :'(encode x)=:y'</lang>
set=:4 :'(encode x)=:y'</syntaxhighlight>


Example use:
Example use:


<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,323: Line 3,323:
get__example 'bletch'
get__example 'bletch'
7 8 9
7 8 9
codestroy__example''</lang>
codestroy__example''</syntaxhighlight>


Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions).
Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions).
Line 3,331: Line 3,331:


Defining the Map:
Defining the Map:
<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);
map.put("baz", 15);
map.put("baz", 15);
map.put("foo", 6);</lang>
map.put("foo", 6);</syntaxhighlight>
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key.
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key.


Initializing a Map as a class member:
Initializing a Map as a class member:
<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);
put("baz", 15);
put("baz", 15);
put("foo", 6);
put("foo", 6);
}};</lang>
}};</syntaxhighlight>
Retrieving a value:
Retrieving a value:
<lang java5>map.get("foo"); // => 6
<syntaxhighlight lang=java5>map.get("foo"); // => 6
map.get("invalid"); // => null</lang>
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:
<lang java5>for (String key: map.keySet())
<syntaxhighlight lang=java5>for (String key: map.keySet())
System.out.println(key);</lang>
System.out.println(key);</syntaxhighlight>
Iterate over values:
Iterate over values:
<lang java5>for (int value: map.values())
<syntaxhighlight lang=java5>for (int value: map.values())
System.out.println(value);</lang>
System.out.println(value);</syntaxhighlight>
Iterate over key, value pairs:
Iterate over key, value pairs:
<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());</lang>
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
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.
<lang javascript>var assoc = {};
<syntaxhighlight lang=javascript>var assoc = {};


assoc['foo'] = 'bar';
assoc['foo'] = 'bar';
Line 3,385: Line 3,385:
alert('key:"' + key + '", value:"' + assoc[key] + '"');
alert('key:"' + key + '", value:"' + assoc[key] + '"');
}
}
}</lang>
}</syntaxhighlight>


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.
<lang javascript>var map = new Map(),
<syntaxhighlight lang=javascript>var map = new Map(),
fn = function () {},
fn = function () {},
obj = {};
obj = {};
Line 3,409: Line 3,409:
for (var key of map.keys()) {
for (var key of map.keys()) {
console.log(key + ' => ' + map.get(key));
console.log(key + ' => ' + map.get(key));
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
===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".
<lang jq># An empty object:
<syntaxhighlight lang=jq># An empty object:
{}
{}


Line 3,435: Line 3,435:


# Alteration of the value of an existing key:
# Alteration of the value of an existing key:
{"A": 65}["A"] = "AA"</lang>
{"A": 65}["A"] = "AA"</syntaxhighlight>


===Associative Arrays with JSON-Valued Keys===
===Associative Arrays with JSON-Valued Keys===
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.
<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,454: Line 3,454:
def getKey(key): .[key|collisionless];
def getKey(key): .[key|collisionless];


def removeKey(key): delpaths( [ [key|collisionless] ] );</lang>
def removeKey(key): delpaths( [ [key|collisionless] ] );</syntaxhighlight>
'''Example''':
'''Example''':
<lang jq>{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</lang>
<syntaxhighlight lang=jq>{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</syntaxhighlight>
produces:
produces:
<lang sh>"two"</lang>
<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.
<lang javascript>var assoc = {};
<syntaxhighlight lang=javascript>var assoc = {};
assoc['foo'] = 'bar';
assoc['foo'] = 'bar';
Line 3,495: Line 3,495:
assoc ==> { "another-key":3, foo:"bar" }
assoc ==> { "another-key":3, foo:"bar" }
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>
{{out}}
{{out}}
<pre>prompt$ jsish -u associativeArray.jsi
<pre>prompt$ jsish -u associativeArray.jsi
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.
<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,529: Line 3,529:
typeof(dict) # type is infered correctly
typeof(dict) # type is infered correctly
# Dict{Char,Int64}
# Dict{Char,Int64}
</syntaxhighlight>
</lang>


=={{header|K}}==
=={{header|K}}==
Keys in a dictionary must be symbols (`symbol).
Keys in a dictionary must be symbols (`symbol).
<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))


/ extracting a value
/ extracting a value
d1[`bar]
d1[`bar]
2</lang>
2</syntaxhighlight>
Another approach.
Another approach.
<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,549: Line 3,549:
.((`zero;0;)
.((`zero;0;)
(`one;1;)
(`one;1;)
(`two;2;))</lang>
(`two;2;))</syntaxhighlight>


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


d2[] / the values
d2[] / the values
0 1 2</lang>
0 1 2</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|Java}}
{{trans|Java}}
<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,585: Line 3,585:
// iterate over key, value pairs:
// iterate over key, value pairs:
for ((k, v) in map) println("$k => $v")
for ((k, v) in map) println("$k => $v")
}</lang>
}</syntaxhighlight>


=={{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.
<lang scheme>
<syntaxhighlight lang=scheme>


1) a (currently) reduced set of functions:
1) a (currently) reduced set of functions:
Line 3,647: Line 3,647:
bar: Barcelona, Catalunya
bar: Barcelona, Catalunya
]
]
</syntaxhighlight>
</lang>


=={{header|Lang5}}==
=={{header|Lang5}}==
<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,666: Line 3,666:
'bar over at .
'bar over at .
'hello 'bar rot set-at
'hello 'bar rot set-at
20 'baz rot set-at .</lang>
20 'baz rot set-at .</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
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.


<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,682: Line 3,682:
# using an alternate value in case of invalid index; prevents exception
# using an alternate value in case of invalid index; prevents exception
writeln .hash[1; 42]
writeln .hash[1; 42]
writeln .hash[2; 42]</lang>
writeln .hash[2; 42]</syntaxhighlight>


{{out}}
{{out}}
Line 3,692: Line 3,692:


=={{header|Lasso}}==
=={{header|Lasso}}==
<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,729: Line 3,729:
#1 -> reverse
#1 -> reverse
}
}
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW)</lang>
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW)</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==
<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,739: Line 3,739:
(: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))
(: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict))))


</syntaxhighlight>
</lang>


=={{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>
<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,756: Line 3,756:


print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green")
print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green")
</syntaxhighlight>
</lang>
Key 'green' is associated with data item 50 255 50
Key 'green' is associated with data item 50 255 50


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


put props[#key2]
put props[#key2]
Line 3,769: Line 3,769:
-- "value2"
-- "value2"
put props.getProp(#key2)
put props.getProp(#key2)
-- "value2"</lang>
-- "value2"</syntaxhighlight>


=={{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.
<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,782: Line 3,782:
"length of item 3:" && the length of tArray["abc"] & return & \
"length of item 3:" && the length of tArray["abc"] & return & \
"keys:" && the keys of tArray
"keys:" && the keys of tArray
end assocArray</lang>
end assocArray</syntaxhighlight>
Output
Output
<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
abc
abc
key 1</lang>
key 1</syntaxhighlight>


=={{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.
<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
print gprop "animals "cat ; 5
print gprop "animals "cat ; 5
remprop "animals "dog
remprop "animals "dog
show plist "animals ; [mouse 11 cat 5]</lang>
show plist "animals ; [mouse 11 cat 5]</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==
BUKKITs are associative arrays
BUKKITs are associative arrays
<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,807: Line 3,807:
VISIBLE Hash'Z SRS "key-2"
VISIBLE Hash'Z SRS "key-2"
KTHXBYE
KTHXBYE
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>1</pre>
<pre>1</pre>
Line 3,813: Line 3,813:
=={{header|Lua}}==
=={{header|Lua}}==
Lua tables are Hashes
Lua tables are Hashes
<lang lua>hash = {}
<syntaxhighlight lang=lua>hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
hash[ "key-2" ] = 1
hash[ "key-3" ] = {}</lang>
hash[ "key-3" ] = {}</syntaxhighlight>
Returns nil on unknown key.
Returns nil on unknown key.


=={{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.
<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,843: Line 3,843:
If Exist(A, "End") Then Print Eval(A)=5000
If Exist(A, "End") Then Print Eval(A)=5000


</syntaxhighlight>
</lang>


=={{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.
<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,857: Line 3,857:


> T["foo"];
> T["foo"];
1</lang>
1</syntaxhighlight>
New entries are added by assignment.
New entries are added by assignment.
<lang Maple>> T[ "bar" ] := 2;
<syntaxhighlight lang=Maple>> T[ "bar" ] := 2;
T["bar"] := 2
T["bar"] := 2


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


> T[ "foo" ];
> T[ "foo" ];
T["foo"]</lang>
T["foo"]</syntaxhighlight>
(The latter output indicates that T["foo"] is an unassigned name.)
(The latter output indicates that T["foo"] is an unassigned name.)


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>a[2] = "string"; a["sometext"] = 23;</lang>
<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.


<lang MATLAB> hash.a = 1;
<syntaxhighlight lang=MATLAB> hash.a = 1;
hash.b = 2;
hash.b = 2;
hash.C = [3,4,5]; </lang>
hash.C = [3,4,5]; </syntaxhighlight>
alternatively
alternatively
<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]); </lang>
hash = setfield(hash,'C',[3,4,5]); </syntaxhighlight>
or
or
<lang MATLAB> hash.('a') = 1;
<syntaxhighlight lang=MATLAB> hash.('a') = 1;
hash.('b') = 2;
hash.('b') = 2;
hash.('C') = [3,4,5]; </lang>
hash.('C') = [3,4,5]; </syntaxhighlight>


<pre>>> disp(hash)
<pre>>> disp(hash)
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.
<lang MATLAB>m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</lang>
<syntaxhighlight lang=MATLAB>m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</syntaxhighlight>
is equivalent to
is equivalent to
<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;</lang>
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.
<lang MATLAB>m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</lang>
<syntaxhighlight lang=MATLAB>m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</syntaxhighlight>
is equivalent to
is equivalent to
<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';
m(37) = 'thirtyseven';</lang>
m(37) = 'thirtyseven';</syntaxhighlight>
Usage:
Usage:
<pre>>> m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});
<pre>>> m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});
Line 3,933: Line 3,933:


=={{header|Maxima}}==
=={{header|Maxima}}==
<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,939: Line 3,939:


arrayinfo(h);
arrayinfo(h);
[hashed, 1, [1], [9]]</lang>
[hashed, 1, [1], [9]]</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>{1 :one 2 :two 3 :three}</lang>
<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.
<lang MiniScript>map = { 3: "test", "foo": 42 }
<syntaxhighlight lang=MiniScript>map = { 3: "test", "foo": 42 }


print map[3]
print map[3]
Line 3,954: Line 3,954:
print map["foo"]
print map["foo"]
print map.foo // same as map["foo"] (only for string keys that are valid identifiers)
print map.foo // same as map["foo"] (only for string keys that are valid identifiers)
</syntaxhighlight>
</lang>


=={{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.
<lang Nemerle>using System;
<syntaxhighlight lang=Nemerle>using System;
using System.Console;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections;
Line 3,974: Line 3,974:
WriteLine(hash1[entry]);
WriteLine(hash1[entry]);
}
}
}</lang>
}</syntaxhighlight>


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


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


say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't set
say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't set
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set</lang>
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set</syntaxhighlight>


{{out}}
{{out}}
Line 3,997: Line 3,997:


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


var
var
Line 4,025: Line 4,025:
echo "iterate values:" # iterating over values
echo "iterate values:" # iterating over values
for key in hash.values:
for key in hash.values:
echo key</lang>
echo key</syntaxhighlight>
{{out}}
{{out}}
<pre>hash has 3 elements
<pre>hash has 3 elements
Line 4,045: Line 4,045:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with| oo2c Version 2}}
{{works with| oo2c Version 2}}
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE AssociativeArray;
MODULE AssociativeArray;
IMPORT
IMPORT
Line 4,088: Line 4,088:
END AssociativeArray.
END AssociativeArray.


</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==
Line 4,094: Line 4,094:


=== Associative map===
=== Associative map===
<lang objeck>
<syntaxhighlight lang=objeck>
# create map
# create map
map := StringMap->New();
map := StringMap->New();
Line 4,105: Line 4,105:
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine();
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine();
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine();
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine();
</syntaxhighlight>
</lang>


===Hash table===
===Hash table===
<lang objeck>
<syntaxhighlight lang=objeck>
# create map
# create map
map := StringHash->New();
map := StringHash->New();
Line 4,119: Line 4,119:
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine();
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine();
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine();
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine();
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
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.
<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",
[NSNull null], @"extra",
[NSNull null], @"extra",
nil];</lang>
nil];</syntaxhighlight>


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+) :
<lang objc>NSDictionary *dict = @{
<syntaxhighlight lang=objc>NSDictionary *dict = @{
@"name": @"Joe Doe",
@"name": @"Joe Doe",
@"age": @42,
@"age": @42,
@"extra": [NSNull null],
@"extra": [NSNull null],
};</lang>
};</syntaxhighlight>


To create a mutable dictionary, use NSMutableDictionary:
To create a mutable dictionary, use NSMutableDictionary:
<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"];</lang>
[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.
<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"];</lang>
id missing = [dict objectForKey:@"missing"];</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
===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:
<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];;</lang>
["foo", 5; "bar", 10; "baz", 15];;</syntaxhighlight>
To retrieve a value:
To retrieve a value:
<lang ocaml>let bar = Hashtbl.find hash "bar";; (* bar = 10 *)</lang>
<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:
<lang ocaml>let quux = try Hashtbl.find hash "quux" with Not_found -> some_value;;</lang>
<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:
<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,172: Line 4,172:
StringMap.empty
StringMap.empty
["foo", 5; "bar", 10; "baz", 15]
["foo", 5; "bar", 10; "baz", 15]
;;</lang>
;;</syntaxhighlight>
To retrieve a value:
To retrieve a value:
<lang ocaml>let bar = StringMap.find "bar" map;; (* bar = 10 *)</lang>
<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:
<lang ocaml>let quux = try StringMap.find "quux" map with Not_found -> some_value;;</lang>
<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.
<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,185: Line 4,185:


(* see if key exists *)
(* see if key exists *)
print_endline (if List.mem_assoc "foo" dict then "key found" else "key missing")</lang>
print_endline (if List.mem_assoc "foo" dict then "key found" else "key missing")</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
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.


<lang scheme>
<syntaxhighlight lang=scheme>
;;; empty associative array
;;; empty associative array
#empty
#empty
Line 4,224: Line 4,224:
(print my-new-map)
(print my-new-map)
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value))
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value))
</syntaxhighlight>
</lang>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
Line 4,237: Line 4,237:


Defining the map:
Defining the map:
<lang ooRexx>map = .directory~new
<syntaxhighlight lang=ooRexx>map = .directory~new
map["foo"] = 5
map["foo"] = 5
map["bar"] = 10
map["bar"] = 10
map["baz"] = 15
map["baz"] = 15
map["foo"] = 6
map["foo"] = 6
</syntaxhighlight>
</lang>
"Putting" a value for a key that already exists ("map["foo"] = 6" in this example) will replace and return the old value for the key.
"Putting" a value for a key that already exists ("map["foo"] = 6" in this example) will replace and return the old value for the key.


Retrieving a value:
Retrieving a value:
<lang ooRexx>item = map["foo"] -- => 6
<syntaxhighlight lang=ooRexx>item = map["foo"] -- => 6
item = map["invalid"] -- => .nil</lang>
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:
<lang ooRexx>loop key over map
<syntaxhighlight lang=ooRexx>loop key over map
say key
say key
end
end
</syntaxhighlight>
</lang>
Iterate over values:
Iterate over values:
<lang ooRexx>loop value over map~allItems
<syntaxhighlight lang=ooRexx>loop value over map~allItems
say value
say value
end
end
</syntaxhighlight>
</lang>
Iterate over key, value pairs:
Iterate over key, value pairs:
<lang ooRexx>
<syntaxhighlight lang=ooRexx>
s = map~supplier
s = map~supplier
loop while s~available
loop while s~available
Line 4,267: Line 4,267:
s~next
s~next
end
end
</syntaxhighlight>
</lang>


=={{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.
<lang oxygenbasic>
<syntaxhighlight lang=oxygenbasic>
def n 200
def n 200


Line 4,324: Line 4,324:
A.dat("computers")="LC99" '
A.dat("computers")="LC99" '
print A.dat("computers") 'result LC99
print A.dat("computers") 'result LC99
</syntaxhighlight>
</lang>


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


{Inspect Dict}</lang>
{Inspect Dict}</syntaxhighlight>


'Records' can be consideres immutable maps:
'Records' can be consideres immutable maps:
<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
{Inspect Rec}</lang>
{Inspect Rec}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
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:
<lang parigp>M = Map();</lang>
<syntaxhighlight lang=parigp>M = Map();</syntaxhighlight>
They can be used as follows:
They can be used as follows:
<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);
mapget(M, "key2") \\ returns Pi
mapget(M, "key2") \\ returns Pi
mapisdefined(M, "key3") \\ returns 0
mapisdefined(M, "key3") \\ returns 0
mapdelete(M, "key2");</lang>
mapdelete(M, "key2");</syntaxhighlight>


In PARI the commands are <code>gtomap</code>, <code>mapput</code>, <code>mapget</code>, <code>mapisdefined</code>, and <code>mapdelete</code>. You can also use the solutions in [[Associative arrays/Creation/C]].
In PARI the commands are <code>gtomap</code>, <code>mapput</code>, <code>mapget</code>, <code>mapisdefined</code>, and <code>mapdelete</code>. You can also use the solutions in [[Associative arrays/Creation/C]].
Line 4,362: Line 4,362:
===Hash===
===Hash===
Definition:
Definition:
<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,376: Line 4,376:
'three', -238.83,
'three', -238.83,
4, 'val3',
4, 'val3',
);</lang>
);</syntaxhighlight>


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


$hash{key1} = 'val1';
$hash{key1} = 'val1';


@hash{'key1', 'three'} = ('val1', -238.83);</lang>
@hash{'key1', 'three'} = ('val1', -238.83);</syntaxhighlight>
===HashRef===
===HashRef===
Definition:
Definition:
<lang perl>my $hashref = {
<syntaxhighlight lang=perl>my $hashref = {
key1 => 'val1',
key1 => 'val1',
'key-2' => 2,
'key-2' => 2,
three => -238.83,
three => -238.83,
4 => 'val3',
4 => 'val3',
}</lang>
}</syntaxhighlight>


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


$hashref->{key1} = 'val1';
$hashref->{key1} = 'val1';


@{$hashref}{('key1', 'three')} = ('val1', -238.83);</lang>
@{$hashref}{('key1', 'three')} = ('val1', -238.83);</syntaxhighlight>


===Key Types===
===Key Types===
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).
<!--<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,426: Line 4,426:
<span style="color: #7060A8;">deld</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">deld</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 0</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 0</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<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,463: Line 4,463:
PI getd tostr print nl
PI getd tostr print nl
3 getd print
3 getd print
</syntaxhighlight>
</lang>


=={{header|PHP}}==
=={{header|PHP}}==
<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,486: Line 4,486:
// Check if key exists in the associative array
// Check if key exists in the associative array
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null</lang>
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null</syntaxhighlight>


===Iterate over key/value===
===Iterate over key/value===
<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";
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Associative arrays are called "map" in Picat.
Associative arrays are called "map" in Picat.
<lang Picat>go =>
<syntaxhighlight lang=Picat>go =>


% Create an empty map
% Create an empty map
Line 4,532: Line 4,532:


nl.
nl.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
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].


<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,566: Line 4,566:
foo 20
foo 20
bar 10
bar 10
baz 15</lang>
baz 15</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
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.
<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,586: Line 4,586:
values(m),
values(m),
m[17]);
m[17]);
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
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.
<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",
m2->car->ford,
m2->car->ford,
m2["car"]["volvo"]);
m2["car"]["volvo"]);
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,614: Line 4,614:


=={{header|PL/I}}==
=={{header|PL/I}}==
<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,662: Line 4,662:
End;
End;


End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>added >1< -> spam<
<pre>added >1< -> spam<
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:-
<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,695: Line 4,695:
dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize);
dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize);
END;
END;
/</lang>
/</syntaxhighlight>


=={{header|Pop11}}==
=={{header|Pop11}}==
<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,719: Line 4,719:
printf(value, '%p\t');
printf(value, '%p\t');
printf(key, '%p\n');
printf(key, '%p\n');
endprocedure);</lang>
endprocedure);</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang postscript>
<syntaxhighlight lang=postscript>
<</a 100 /b 200 /c 300>>
<</a 100 /b 200 /c 300>>
dup /a get =
dup /a get =
</syntaxhighlight>
</lang>


=={{header|Potion}}==
=={{header|Potion}}==
<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,735: Line 4,735:
255 == mydictionary("blue")
255 == mydictionary("blue")
65280 == mydictionary("green")
65280 == mydictionary("green")
16711935 == mydictionary("purple")</lang>
16711935 == mydictionary("purple")</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
An empty hash table can be created with:
An empty hash table can be created with:
<lang powershell>$hashtable = @{}</lang>
<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:
<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.
}</lang>
}</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:
<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</lang>
$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:
<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,770: Line 4,770:
---- -----
---- -----
A 2
A 2
a 1 </lang>
a 1 </syntaxhighlight>
Similarly, values can be retrieved using either syntax:
Similarly, values can be retrieved using either syntax:
<lang powershell>$hashtable.key1 # value 1
<syntaxhighlight lang=powershell>$hashtable.key1 # value 1
$hashtable['key2'] # 5</lang>
$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:
<lang powershell>$obj = [PSCustomObject]@{
<syntaxhighlight lang=powershell>$obj = [PSCustomObject]@{
"key1" = "value 1"
"key1" = "value 1"
key2 = 5
key2 = 5
}</lang>
}</syntaxhighlight>
This is a convenience syntax, has less code and runs faster than other ways to create objects.
This is a convenience syntax, has less code and runs faster than other ways to create objects.


=={{header|Prolog}}==
=={{header|Prolog}}==
We use the facts table for this purpose.
We use the facts table for this purpose.
<lang prolog>
<syntaxhighlight lang=prolog>
mymap(key1,value1).
mymap(key1,value1).
mymap(key2,value2).
mymap(key2,value2).
Line 4,789: Line 4,789:
?- mymap(key1,V).
?- mymap(key1,V).
V = value1
V = value1
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Hashes are a built-in type called Map in Purebasic.
Hashes are a built-in type called Map in Purebasic.


<lang purebasic>NewMap dict.s()
<syntaxhighlight lang=purebasic>NewMap dict.s()
dict("country") = "Germany"
dict("country") = "Germany"
Debug dict("country")</lang>
Debug dict("country")</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Hashes are a built-in type called dictionaries (or mappings) in Python.
Hashes are a built-in type called dictionaries (or mappings) in Python.


<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, }
value = hash[key]</lang>
value = hash[key]</syntaxhighlight>


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


<lang python># empty dictionary
<syntaxhighlight lang=python># empty dictionary
d = {}
d = {}
d['spam'] = 1
d['spam'] = 1
Line 4,827: Line 4,827:
# iterating over (key, value) pairs
# iterating over (key, value) pairs
for key, value in d.iteritems():
for key, value in d.iteritems():
print key, value</lang>
print key, value</syntaxhighlight>


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:


<lang python>myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }</lang>
<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 ===


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


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


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


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


<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)</lang>
> print(a)</syntaxhighlight>
<pre>$a
<pre>$a
[1] 1
[1] 1
Line 4,885: Line 4,885:
$d
$d
[1] "xyz"</pre>
[1] "xyz"</pre>
<lang r>> print(names(a))</lang>
<syntaxhighlight lang=r>> print(names(a))</syntaxhighlight>
<pre>[1] "a" "b" "c" "d"</pre>
<pre>[1] "a" "b" "c" "d"</pre>
<lang r>> print(unname(a))</lang>
<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.


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


Line 4,917: Line 4,917:
(dict-ref a-list 'a) ; => 5
(dict-ref a-list 'a) ; => 5
(dict-ref table 'a) ; => 5
(dict-ref table 'a) ; => 5
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
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.


<lang perl6>my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
<syntaxhighlight lang=perl6>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,952: Line 4,952:
class C {};
class C {};
my %cash{C};
my %cash{C};
%cash{C.new} = 1;</lang>
%cash{C.new} = 1;</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==
<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,967: Line 4,967:
6.28 a_hash 'c' set # set key 'c'
6.28 a_hash 'c' set # set key 'c'
a_hash.'c' # get key 'c' shorthand
a_hash.'c' # get key 'c' shorthand
6.28 a_hash:'c' # set key 'c' shorthand</lang>
6.28 a_hash:'c' # set key 'c' shorthand</syntaxhighlight>


Null is returned for unknown keys.
Null is returned for unknown keys.
Line 4,973: Line 4,973:


=={{header|Relation}}==
=={{header|Relation}}==
<lang relation>
<syntaxhighlight lang=relation>
relation key, value
relation key, value
insert "foo", "bar"
insert "foo", "bar"
Line 4,982: Line 4,982:
select key == "fruit"
select key == "fruit"
print
print
</syntaxhighlight>
</lang>


'''assert''' will show an error, if a key is used twice. However, it not stop the insertion.
'''assert''' will show an error, if a key is used twice. However, it not stop the insertion.
Line 5,005: Line 5,005:


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


Line 5,012: Line 5,012:


table @" first" putn
table @" first" putn
table @" second" puts</lang>
table @" second" puts</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===version 1===
===version 1===
Associative arrays are called ''stem variables'' in Rexx.
Associative arrays are called ''stem variables'' in Rexx.
<lang Rexx>/* Rexx */
<syntaxhighlight lang=Rexx>/* Rexx */


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


Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */
Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */
Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */</lang>
Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */</syntaxhighlight>
{{out}}
{{out}}
<pre>stem.key0= .
<pre>stem.key0= .
Line 5,032: Line 5,032:


===version 2===
===version 2===
<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,058: Line 5,058:
yyy='RI'
yyy='RI'
say 'capital of' stateN.yyy "is" stateC.yyy
say 'capital of' stateN.yyy "is" stateC.yyy
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 5,067: Line 5,067:


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


Line 5,075: Line 5,075:
see find(myarray,"two",1) + nl
see find(myarray,"two",1) + nl
see find(myarray,2,2) + nl
see find(myarray,2,2) + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,084: Line 5,084:
=={{header|RLaB}}==
=={{header|RLaB}}==
Associative arrays are called ''lists'' in RLaB.
Associative arrays are called ''lists'' in RLaB.
<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,110: Line 5,110:
{ x.[i] = i; } // assign to the element of list ''i'' the real value equal to i.
{ x.[i] = i; } // assign to the element of list ''i'' the real value equal to i.


</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
A hash object that returns [[nil]] for unknown keys
A hash object that returns [[nil]] for unknown keys
<lang ruby>hash={}
<syntaxhighlight lang=ruby>hash={}
hash[666]='devil'
hash[666]='devil'
hash[777] # => nil
hash[777] # => nil
hash[666] # => 'devil'</lang>
hash[666] # => 'devil'</syntaxhighlight>


A hash object that returns 'unknown key' for unknown keys
A hash object that returns 'unknown key' for unknown keys
<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'
hash[666] # => 'devil'</lang>
hash[666] # => 'devil'</syntaxhighlight>


A hash object that returns "unknown key #{key}" for unknown keys
A hash object that returns "unknown key #{key}" for unknown keys
<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'
hash[666] # => 'devil'</lang>
hash[666] # => 'devil'</syntaxhighlight>


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
<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'
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'</lang>
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<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,146: Line 5,146:
olympic_medals.insert("Germany", (252, 260, 270));
olympic_medals.insert("Germany", (252, 260, 270));
println!("{:?}", olympic_medals);
println!("{:?}", olympic_medals);
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<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,169: Line 5,169:
end;
end;
end;
end;
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<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
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true</lang>
map.isDefinedAt(44) // true</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,188: Line 5,188:
hash.contains(33) // false
hash.contains(33) // false
hash.isDefinedAt(33) // same as contains
hash.isDefinedAt(33) // same as contains
hash.contains(44) // true</lang>
hash.contains(44) // true</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)</lang>
for((k,v) <- hash) println("key " + k + " value " + v)</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
for((k, v) <- map; if k > 3) yield (k,v)</lang>
for((k, v) <- map; if k > 3) yield (k,v)</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==


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.
<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)</lang>
(assoc 'a my-dict) ; evaluates to '(a b)</syntaxhighlight>




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.


<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))</lang>
(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.


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


(import (rnrs base)
(import (rnrs base)
Line 5,222: Line 5,222:
(hashtable-set! my-hash 'a 'b)
(hashtable-set! my-hash 'a 'b)
(hashtable-set! my-hash 1 'hello)
(hashtable-set! my-hash 1 'hello)
(hashtable-set! my-hash "c" '(a b c))</lang>
(hashtable-set! my-hash "c" '(a b c))</syntaxhighlight>


=== A ''persistent'' associative array from scratch ===
=== A ''persistent'' associative array from scratch ===
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.


<lang scheme>(cond-expand
<syntaxhighlight lang=scheme>(cond-expand
(r7rs)
(r7rs)
(chicken (import r7rs)))
(chicken (import r7rs)))
Line 5,618: Line 5,618:


))
))
(else))</lang>
(else))</syntaxhighlight>


{{out}}
{{out}}
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.


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


# Define hash type
# Define hash type
Line 5,686: Line 5,686:
writeln("key: " <& stri <& ", value: " <& number);
writeln("key: " <& stri <& ", value: " <& number);
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
Associative arrays in SenseTalk are called property lists, or objects.
Associative arrays in SenseTalk are called property lists, or objects.
<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,698: Line 5,698:
put "!!!" after the occupation of Einstein
put "!!!" after the occupation of Einstein
put Einstein
put Einstein
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
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:
<lang setl>m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};</lang>
<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:
<lang setl>print( m('bar') );</lang>
<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):
<lang setl>print( m{'bar'} );</lang>
<syntaxhighlight lang=setl>print( m{'bar'} );</syntaxhighlight>
{{out}}
{{out}}
<pre>{b}</pre>
<pre>{b}</pre>


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


Line 5,742: Line 5,742:
out('next domain entry',next(d)) :s(next)
out('next domain entry',next(d)) :s(next)
done
done
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var hash = Hash.new(
<syntaxhighlight lang=ruby>var hash = Hash.new(
key1 => 'value1',
key1 => 'value1',
key2 => 'value2',
key2 => 'value2',
Line 5,751: Line 5,751:


# Add a new key-value pair
# Add a new key-value pair
hash{:key3} = 'value3';</lang>
hash{:key3} = 'value3';</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</lang>
<syntaxhighlight lang=slate>Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</syntaxhighlight>


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


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


=={{header|SQL}}==
=={{header|SQL}}==
<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,783: Line 5,783:
REM Retrieve a key value pair
REM Retrieve a key value pair
SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY';
SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY';
</syntaxhighlight>
</lang>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}} version 9.7 or higher.
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
With SQL PL:
<lang sql pl>
<syntaxhighlight lang=sql pl>
--#SET TERMINATOR @
--#SET TERMINATOR @


Line 5,807: Line 5,807:
CALL DBMS_OUTPUT.PUT_LINE(HASH['5']);
CALL DBMS_OUTPUT.PUT_LINE(HASH['5']);
END@
END@
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 5,827: Line 5,827:


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


Line 5,844: Line 5,844:


// End Mata session
// End Mata session
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<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,859: Line 5,859:


// make a map with a literal
// make a map with a literal
var d = ["foo": 2, "bar": 42, "baz": -1]</lang>
var d = ["foo": 2, "bar": 42, "baz": -1]</syntaxhighlight>


=={{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.
<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
#- 'name' $hash | delete 'name=bob' from hash
#- 'name' $hash | delete 'name=bob' from hash
</syntaxhighlight>
</lang>
=={{header|Tcl}}==
=={{header|Tcl}}==
All arrays in Tcl are associative.
All arrays in Tcl are associative.


<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,887: Line 5,887:
foreach key [array names hash] {
foreach key [array names hash] {
puts $hash($key)
puts $hash($key)
}</lang>
}</syntaxhighlight>


Tcl also provides associative map values (called “dictionaries”) from 8.5 onwards.
Tcl also provides associative map values (called “dictionaries”) from 8.5 onwards.
<br>
<br>
{{works with|Tcl|8.5}}
{{works with|Tcl|8.5}}
<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,911: Line 5,911:


# Output the whole dictionary (since it is a Tcl value itself)
# Output the whole dictionary (since it is a Tcl value itself)
puts $d</lang>
puts $d</syntaxhighlight>


=={{header|Toka}}==
=={{header|Toka}}==
Toka provides associative arrays via a library.
Toka provides associative arrays via a library.


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


( create an associative array )
( create an associative array )
Line 5,929: Line 5,929:
( obtain and print the values )
( obtain and print the values )
" first" foo asarray.get .
" first" foo asarray.get .
" second" foo asarray.get .</lang>
" second" foo asarray.get .</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|ksh}}
{{works with|ksh}}
<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
echo "${hash[key3]}"</lang>
echo "${hash[key3]}"</syntaxhighlight>


{{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:
<lang bash>declare -A hash</lang>
<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
<lang bash>map='p.map'
<syntaxhighlight lang=bash>map='p.map'


function init() {
function init() {
Line 5,987: Line 5,987:
put c cow
put c cow
get c
get c
dump</lang>
dump</syntaxhighlight>


=={{header|Vala}}==
=={{header|Vala}}==
{{libheader|Gee}}
{{libheader|Gee}}
<lang vala>
<syntaxhighlight lang=vala>
using Gee;
using Gee;


Line 6,009: Line 6,009:
stdout.printf("%d\n", map.get("two"));
stdout.printf("%d\n", map.get("two"));
}
}
</syntaxhighlight>
</lang>


Compile with flag: <pre> --pkg gee-1.0 </pre>
Compile with flag: <pre> --pkg gee-1.0 </pre>
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.


<lang vb>Option Explicit
<syntaxhighlight lang=vb>Option Explicit
Sub Test()
Sub Test()
Dim h As Object
Dim h As Object
Line 6,031: Line 6,031:
h.RemoveAll
h.RemoveAll
Debug.Print h.Count
Debug.Print h.Count
End Sub</lang>
End Sub</syntaxhighlight>


=={{header|Vim Script}}==
=={{header|Vim Script}}==
Dictionary keys are always strings.
Dictionary keys are always strings.
<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,054: Line 6,054:
let one = remove(dict, "one")
let one = remove(dict, "one")
unlet dict["two"]
unlet dict["two"]
unlet dict.three</lang>
unlet dict.three</syntaxhighlight>


=={{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.
<lang vfp>
<syntaxhighlight lang=vfp>
LOCAL loCol As Collection, k, n, o
LOCAL loCol As Collection, k, n, o
CLEAR
CLEAR
Line 6,098: Line 6,098:
ENDPROC
ENDPROC
ENDDEFINE
ENDDEFINE
</syntaxhighlight>
</lang>


=={{header|Vlang}}==
=={{header|Vlang}}==
<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,120: Line 6,120:
'baz': -1
'baz': -1
}
}
}</lang>
}</syntaxhighlight>


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>h <- (table 'a 1 'b 2)
<syntaxhighlight lang=wart>h <- (table 'a 1 'b 2)
h 'a
h 'a
=> 1</lang>
=> 1</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
Wren has a Map class built in.
Wren has a Map class built in.
<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,146: Line 6,146:
System.print(capitals) // prints all remaining entries
System.print(capitals) // prints all remaining entries
System.print(capitals.count) // prints the number of remaining entries
System.print(capitals.count) // prints the number of remaining entries
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one)</lang>
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one)</syntaxhighlight>


{{out}}
{{out}}
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:
<lang lisp>(define starlings (make-table))</lang>
<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>:
<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")</lang>
(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:
<lang lisp>(table-ref starlings "Cape starling")</lang>
<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:
<lang lisp>(map-over-table-entries starlings (lambda (x y) (print (string-append x " (Linnaean name " y ")"))))</lang>
<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}}==
<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,205: Line 6,205:
ChOut(0, Lookup("beta")); CrLf(0);
ChOut(0, Lookup("beta")); CrLf(0);
ChOut(0, Lookup("omega")); CrLf(0);
ChOut(0, Lookup("omega")); CrLf(0);
]</lang>
]</syntaxhighlight>


For greater speed a hashing algorithm should be used to look up items in
For greater speed a hashing algorithm should be used to look up items in
Line 6,218: Line 6,218:


=={{header|zkl}}==
=={{header|zkl}}==
<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)


zkl: T("one",1, "two",2, "three",3).toDictionary()
zkl: T("one",1, "two",2, "three",3).toDictionary()
D(two:2,three:3,one:1)</lang>
D(two:2,three:3,one:1)</syntaxhighlight>


{{omit from|Applesoft BASIC}}
{{omit from|Applesoft BASIC}}