Associative array/Iteration: Difference between revisions

→‎{{header|Oberon-2}}: Fixed "Works with" and syntax highlight with Modula-2
(→‎{{header|Oberon-2}}: Fixed "Works with" and syntax highlight with Modula-2)
 
(129 intermediate revisions by 68 users not shown)
Line 1:
{{task|Basic language learning}}[[Category:Iteration]][[Category:Data Structures]]
[[Category:Data Structures]]
Show how to iterate over the key-value pairs of an associative array,
{{task|Basic language learning}}Show how to iterate over the key-value pairs of an associative array, and print each pair out.
and print each pair out.
 
Also show how to iterate just over the keys, or the values,
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
 
 
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">V d = [‘key1’ = ‘value1’, ‘key2’ = ‘value2’]
 
L(key, value) d
print(key‘ = ’value)
 
L(key) d.keys()
print(key)
 
L(value) d.values()
print(value)</syntaxhighlight>
{{out}}
<pre>
key1 = value1
key2 = value2
key1
key2
value1
value2
</pre>
 
=={{header|8th}}==
Iterating key,value pairs uses "m:each":
<syntaxhighlight lang="forth">
{"one": 1, "two": "bad"}
( swap . space . cr )
m:each
</syntaxhighlight>
{{out}}<pre>
one 1
two bad
</pre>
 
Iterating the keys uses "m:keys":
<syntaxhighlight lang="forth">
{"one": 1, "two": "bad"} m:keys
( . cr )
a:each
</syntaxhighlight>
{{out}}<pre>
one
two
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;
 
Line 25 ⟶ 72:
Index := Next (Index);
end loop;
end Test_Iteration;</langsyntaxhighlight>
{{out}}
<pre>
Line 34 ⟶ 81:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">record r;
text s;
 
Line 44 ⟶ 91:
do {
o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s));
} while (r_greaterrsk_greater(r, s, s));
}</langsyntaxhighlight>
{{out}}
<pre>key A, value 33 (integer)
key B, value associative (text)
key C, value 2.5 (real)</pre>
 
=={{header|ALGOL 68}}==
Algol 68 does not have associative arrays as standard.
<br>
This sample defines a simple hash-based implementation with operators to iterate over the array.
<syntaxhighlight lang="algol68"># associative array handling using hashing #
 
# the modes allowed as associative array element values - change to suit #
MODE AAVALUE = STRING;
# the modes allowed as associative array element keys - change to suit #
MODE AAKEY = STRING;
# nil element value #
REF AAVALUE nil value = NIL;
 
# an element of an associative array #
MODE AAELEMENT = STRUCT( AAKEY key, REF AAVALUE value );
# a list of associative array elements - the element values with a #
# particular hash value are stored in an AAELEMENTLIST #
MODE AAELEMENTLIST = STRUCT( AAELEMENT element, REF AAELEMENTLIST next );
# nil element list reference #
REF AAELEMENTLIST nil element list = NIL;
# nil element reference #
REF AAELEMENT nil element = NIL;
 
# the hash modulus for the associative arrays #
INT hash modulus = 256;
 
# generates a hash value from an AAKEY - change to suit #
OP HASH = ( STRING key )INT:
BEGIN
INT result := ABS ( UPB key - LWB key ) MOD hash modulus;
FOR char pos FROM LWB key TO UPB key DO
result PLUSAB ( ABS key[ char pos ] - ABS " " );
result MODAB hash modulus
OD;
result
END; # HASH #
 
# a mode representing an associative array #
MODE AARRAY = STRUCT( [ 0 : hash modulus - 1 ]REF AAELEMENTLIST elements
, INT curr hash
, REF AAELEMENTLIST curr position
);
 
# initialises an associative array so all the hash chains are empty #
OP INIT = ( REF AARRAY array )REF AARRAY:
BEGIN
FOR hash value FROM 0 TO hash modulus - 1 DO ( elements OF array )[ hash value ] := nil element list OD;
array
END; # INIT #
 
# gets a reference to the value corresponding to a particular key in an #
# associative array - the element is created if it doesn't exist #
PRIO // = 1;
OP // = ( REF AARRAY array, AAKEY key )REF AAVALUE:
BEGIN
REF AAVALUE result;
INT hash value = HASH key;
# get the hash chain for the key #
REF AAELEMENTLIST element := ( elements OF array )[ hash value ];
# find the element in the list, if it is there #
BOOL found element := FALSE;
WHILE ( element ISNT nil element list )
AND NOT found element
DO
found element := ( key OF element OF element = key );
IF found element
THEN
result := value OF element OF element
ELSE
element := next OF element
FI
OD;
IF NOT found element
THEN
# the element is not in the list #
# - add it to the front of the hash chain #
( elements OF array )[ hash value ]
:= HEAP AAELEMENTLIST
:= ( HEAP AAELEMENT := ( key
, HEAP AAVALUE := ""
)
, ( elements OF array )[ hash value ]
);
result := value OF element OF ( elements OF array )[ hash value ]
FI;
result
END; # // #
 
# returns TRUE if array contains key, FALSE otherwise #
PRIO CONTAINSKEY = 1;
OP CONTAINSKEY = ( REF AARRAY array, AAKEY key )BOOL:
BEGIN
# get the hash chain for the key #
REF AAELEMENTLIST element := ( elements OF array )[ HASH key ];
# find the element in the list, if it is there #
BOOL found element := FALSE;
WHILE ( element ISNT nil element list )
AND NOT found element
DO
found element := ( key OF element OF element = key );
IF NOT found element
THEN
element := next OF element
FI
OD;
found element
END; # CONTAINSKEY #
 
# gets the first element (key, value) from the array #
OP FIRST = ( REF AARRAY array )REF AAELEMENT:
BEGIN
curr hash OF array := LWB ( elements OF array ) - 1;
curr position OF array := nil element list;
NEXT array
END; # FIRST #
 
# gets the next element (key, value) from the array #
OP NEXT = ( REF AARRAY array )REF AAELEMENT:
BEGIN
WHILE ( curr position OF array IS nil element list )
AND curr hash OF array < UPB ( elements OF array )
DO
# reached the end of the current element list - try the next #
curr hash OF array +:= 1;
curr position OF array := ( elements OF array )[ curr hash OF array ]
OD;
IF curr hash OF array > UPB ( elements OF array )
THEN
# no more elements #
nil element
ELIF curr position OF array IS nil element list
THEN
# reached the end of the table #
nil element
ELSE
# have another element #
REF AAELEMENTLIST found element = curr position OF array;
curr position OF array := next OF curr position OF array;
element OF found element
FI
END; # NEXT #
 
# test the associative array #
BEGIN
# create an array and add some values #
REF AARRAY a1 := INIT LOC AARRAY;
a1 // "k1" := "k1 value";
a1 // "z2" := "z2 value";
a1 // "k1" := "new k1 value";
a1 // "k2" := "k2 value";
a1 // "2j" := "2j value";
# iterate over the values #
REF AAELEMENT e := FIRST a1;
WHILE e ISNT nil element
DO
print( ( " (" + key OF e + ")[" + value OF e + "]", newline ) );
e := NEXT a1
OD
END</syntaxhighlight>
{{out}}
<pre>
(2j)[2j value]
(k1)[new k1 value]
(k2)[k2 value]
(z2)[z2 value]
</pre>
 
=={{header|App Inventor}}==
Line 55 ⟶ 269:
When a list is organized as pairs, the '''lookup in pairs''' block can be used to retrieve an associated value from a key name.<br>
[https://lh3.googleusercontent.com/-Cxw_-XGMRyM/UutOX1bEH9I/AAAAAAAAJ9g/MZotfuSEziY/s1600/CreateIterateLookup.PNG '''<VIEW BLOCKS AND ANDROID APP>''']
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; create a dictionary
d: #[
name: "john"
surname: "doe"
age: 34
]
 
; Iterate over key/value pairs
loop d [key,value][
print ["key =" key ", value =" value]
]
 
print "----"
 
; Iterate over keys
loop keys d [k][
print ["key =" k]
]
 
print "----"
 
; Iterate over values
loop values d [v][
print ["value =" v]
]</syntaxhighlight>
 
{{out}}
 
<pre>key = name , value = john
key = surname , value = doe
key = age , value = 34
----
key = name
key = surname
key = age
----
value = john
value = doe
value = 34</pre>
 
=={{header|ATS}}==
See [[Associative_array/Creation#ATS|Associative_array/Creation#ATS]].
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
From the [http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/objects/Enumerator.htm documentation]<langsyntaxhighlight AutoHotkeylang="autohotkey">; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t</langsyntaxhighlight>
 
=={{header|AWK}}==
In AWK "arrays" are always associative arrays, and the only way to iterate over them is by keys (''indexes'' in the AWK terminology), in undefined order.
<syntaxhighlight lang="awk">BEGIN {
 
<lang awk>BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
 
# iterate over keys, undefined order
for(key in a) {
print key, a[key]
}
}</langsyntaxhighlight>
 
As AWK was often used in (Bourne) shell scripts,
sorting was done by a pipe of two awk programs and the sort command.
Today, 'gawk' allows to set the order of iteration:
<syntaxhighlight lang="awk">BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
PROCINFO["sorted_in"] = "@ind_str_asc" # controls index order
# iterate over keys, indices as strings sorted ascending
for(key in a) {
print key, a[key]
}
}</syntaxhighlight>
 
=={{header|Babel}}==
 
In Babel, associative arrays are referred to as maps. To create a map from a list-of-lists:
Use the entsha (mnemonic: "get entries from the hash") operator to obtain a list of all entries, where each entry consists of a 3-element list containing the hashed-key, the key and the value in that order.
 
<syntaxhighlight lang="babel">births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! <</syntaxhighlight>
<lang babel>((main
{ (('foo' 12)
('bar' 33)
('baz' 42))
mkhash !
 
To iterate over a map, in the primary sense, use the overmap utility. We will copy the map (cp operator) so as not to modify the original:
entsha
dup
{1 ith nl <<} each
 
<syntaxhighlight lang="babel">births cp dup {1 +} overmap !</syntaxhighlight>
"-----\n" <<
 
To see the results, use the valmap operator:
{2 ith %d nl <<} each})
 
<syntaxhighlight lang="babel">valmap ! lsnum !</syntaxhighlight>
(mkhash
{ <- newha ->
{ <- dup ->
dup 1 ith
<- 0 ith ->
inskha }
each }))</lang>
 
This program generates the following
{{out}}
<pre>( 1918 1733 1883 1810 )</pre>
<pre>foo
baz
bar
-----
12
42
33</pre>
 
There are many ways to interact with a map in Babel. Most of these begin by converting the map to a list or list-of-lists. To look up a list of specific values from the map, by key, use the lumapls utility:
Note that the entsha operator does not return the entries of the hash in any particular order. In general, there is no automatic way to recover the order in which the entries were inserted into the hash.
 
<syntaxhighlight lang="babel">births ('Roosevelt' 'Kennedy') lumapls ! lsnum !</syntaxhighlight>
 
{{out}}
<pre>( 1882 1917 )</pre>
 
To convert the entire map back to a list of key-value pairs:
 
<syntaxhighlight lang="babel">births map2ls !</syntaxhighlight>
 
To view the list:
 
<syntaxhighlight lang="babel">{give swap << " " << itod << "\n" <<} each</syntaxhighlight>
 
{{out}}
<pre>Kennedy 1917
Washington 1732
Roosevelt 1882
Lincoln 1809</pre>
 
To merge two maps together, use the mapmerge utility:
 
<syntaxhighlight lang="babel">foo (("bar" 17) ("baz" 42)) ls2map ! <
births foo mergemap !</syntaxhighlight>
 
To view the results:
 
<syntaxhighlight lang="babel">births map2ls ! {give swap << " " << itod << "\n" <<} each</syntaxhighlight>
 
{{out}}
<pre>baz 42
Kennedy 1917
bar 17
Washington 1732
Roosevelt 1882
Lincoln 1809</pre>
 
For more information on maps in Babel, view [https://github.com/claytonkb/clean_babel/blob/master/std.sp std.sp] (see the section titled "map utilities").
 
=={{header|BASIC}}==
==={{header|BaCon}}===
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING
 
associative("abc") = "first three"
associative("mn") = "middle two"
associative("xyz") = "last three"
 
LOOKUP associative TO keys$ SIZE amount
FOR i = 0 TO amount - 1
PRINT keys$[i], ":", associative(keys$[i])
NEXT</syntaxhighlight>
 
{{out}}
<pre>prompt$ ./assoc
abc:first three
mn:middle two
xyz:last three</pre>
LOOKUP creates a numerically indexed array of the keys of the associative array, with the number of elements stored in the field following the SIZE keyword.
 
==={{header|BASIC256}}===
''Solution is at [[Associative_array/Creation#BASIC256]]''.
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
Line 146 ⟶ 457:
key$ = MID$(dict$, J%+1, K%-J%-1)
IF K% >= LEN(dict$) THEN K% = 0
= K%</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">( new$hash:?myhash
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
Line 166 ⟶ 477:
& put$\n
)
);</langsyntaxhighlight>
{{out}}
<pre>key: meat
Line 184 ⟶ 495:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">h = [ hello: 1 world: 2 :! : 3]
 
#Iterate over key, value pairs
Line 199 ⟶ 510:
h.each_value { v |
p "Value: #{v}"
}</langsyntaxhighlight>
 
=={{header|C}}==
''Solution is at [[Associative arrays/Creation/C]]''.
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
 
Dictionary<string,int> assocArray = new Dictionary<string,int>();
 
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
 
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
 
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
 
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
</syntaxhighlight>
 
=={{header|C++}}==
{{works with|C++11}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <string>
Line 226 ⟶ 573:
 
return 0;
}</langsyntaxhighlight>
 
 
Pre C++11:
<langsyntaxhighlight lang="cpp">std::map<std::string, int> myDict;
myDict["hello"] = 1;
myDict["world"] = 2;
Line 241 ⟶ 588:
int& value = it->second;
std::cout << "key = " << key << ", value = " << value << std::endl;
}</langsyntaxhighlight>
 
=={{header|C sharpCeylon}}==
<syntaxhighlight lang="ceylon">shared void run() {
<lang csharp>using System;
using System.Collections.Generic;
 
value myMap = map {
namespace AssocArrays
"foo" -> 5,
{
"bar" -> 10,
class Program
"baz" -> 15
{
};
static void Main(string[] args)
{
for(key in myMap.keys) {
 
print(key);
Dictionary<string,int> assocArray = new Dictionary<string,int>();
}
 
assocArray["Hello"] = 1;
for(item in myMap.items) {
assocArray.Add("World", 2);
print(item);
assocArray["!"] = 3;
}
 
foreach (KeyValuePair<string, int> kvp in assocArray)
for(key->item in myMap) {
{
print("``key`` maps to ``item``");
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
}
 
}</syntaxhighlight>
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
 
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}
</lang>
 
=={{header|Chapel}}==
 
<langsyntaxhighlight lang="chapel">var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ];
 
for k in A.domain do
Line 290 ⟶ 624:
 
for (k,v) in zip(A.domain, A) do
writeln("have element: ", k, " -> ", v);</langsyntaxhighlight>
 
{{out}}
Line 304 ⟶ 638:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
(doseq [[k v] {:a 1, :b 2, :c 3}]
(println k "=" v))
Line 313 ⟶ 647:
(doseq [v (vals {:a 1, :b 2, :c 3})]
(println v))
</syntaxhighlight>
</lang>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">hash =
a: 'one'
b: 'two'
Line 325 ⟶ 659:
for key of hash
console.log key
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 334 ⟶ 668:
The association list is a list of conses, each of whose <code>car</code> is a key and whose <code>cdr</code> is a value. The standard mapping and print functions can be used to print key/value pairs, keys, and values.
 
<langsyntaxhighlight lang="lisp">;; iterate using dolist, destructure manually
(dolist (pair alist)
(destructuring-bind (key . value) pair
Line 341 ⟶ 675:
;; iterate and destructure with loop
(loop for (key . value) in alist
do (format t "~&Key: ~a, Value: ~a." key value))</langsyntaxhighlight>
 
===With property lists (plists)===
Line 347 ⟶ 681:
Property lists are lists of alternating keys and values, where each value's key is the element of the list immediately following it. Printing could be done with standard mapping functions, but <code>loop</code>'s destructuring makes things a bit easier.
 
<langsyntaxhighlight lang="lisp">(loop for (key value) on plist :by 'cddr
do (format t "~&Key: ~a, Value: ~a." key value))</langsyntaxhighlight>
 
===With hash tables===
Line 354 ⟶ 688:
Lisp also has built-in hash tables, and there are several ways to map over these. The first is <code>maphash</code> which takes a function of two arguments (the key and value) and the hash table.
 
<langsyntaxhighlight lang="lisp">(maphash (lambda (key value)
(format t "~&Key: ~a, Value: ~a." key value))
hash-table)</langsyntaxhighlight>
 
The <code>loop</code> construct also supports extracting key/value pairs from hash tables.
 
<langsyntaxhighlight lang="lisp">(loop for key being each hash-key of hash-table using (hash-value value)
do (format t "~&Key: ~a, Value: ~a." key value))</langsyntaxhighlight>
 
There is also a macro <code>with-hash-table-iterator</code> which locally binds a name to produce associated keys and values of the hash table; while rarely used, it is the most powerful operation.
 
<langsyntaxhighlight lang="lisp">(with-hash-table-iterator (next-entry hash-table)
(loop
(multiple-value-bind (nextp key value) (next-entry)
(if (not nextp)
(return)
(format t "~&Key: ~a, Value: ~a." key value)))))</langsyntaxhighlight>
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<syntaxhighlight lang="lisp">
;; Project : Associative array/Iteration
 
(setf x (make-array '(3 2)
:initial-contents '(("hello" 13 ) ("world" 31) ("!" 71))))
(setf xlen (array-dimensions x))
(setf len (car xlen))
(dotimes (n len)
(terpri)
(format t "~a" (aref x n 0))
(format t "~a" " : ")
(format t "~a" (aref x n 1)))
</syntaxhighlight>
Output:
<pre>
hello : 13
world : 31
! : 71
</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">dict = {'A' => 1, 'B' => 2}
 
dict.each { |pair|
puts pair
}
 
dict.each_key { |key|
puts key
}
 
dict.each_value { |value|
puts value
}</syntaxhighlight>
 
{{out}}
<pre>{'A', 1}
{'B', 2}
A
B
1
2</pre>
 
=={{header|D}}==
{{works with|D|2}}
 
<langsyntaxhighlight lang="d">import std.stdio: writeln;
 
void main() {
Line 414 ⟶ 793:
foreach (value; aa.values)
writeln("7) Got value ", value);
}</langsyntaxhighlight>
 
=={{header|Dao}}==
<langsyntaxhighlight lang="ruby">
dict = { 'def' => 1, 'abc' => 2 }
 
Line 425 ⟶ 804:
io.writeln( key, value )
}
</syntaxhighlight>
</lang>
 
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
main(){
var fruits = {
'apples': 'red',
'oranges': 'orange',
'bananas': 'yellow',
'pears': 'green',
'plums': 'purple'
};
print('Key Value pairs:');
fruits.forEach( (fruits, color) => print( '$fruits are $color' ) );
print('\nKeys only:');
fruits.keys.forEach( ( key ) => print( key ) );
print('\nValues only:');
fruits.values.forEach( ( value ) => print( value ) );
}
</syntaxhighlight>
{{out}}
<pre>
Key Value pairs:
apples are red
oranges are orange
bananas are yellow
pears are green
plums are purple
 
Keys only:
apples
oranges
bananas
pears
plums
 
Values only:
red
orange
yellow
green
purple
</pre>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program AssociativeArrayIteration;
 
{$APPTYPE CONSOLE}
Line 456 ⟶ 880:
lDictionary.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">var t = (x: 1, y: 2, z: 3)
 
for x in t.Keys() {
print("\(x)=\(t[x])")
}</syntaxhighlight>
 
{{out}}
 
<pre>x=1
y=2
z=3</pre>
 
=={{header|E}}==
Line 464 ⟶ 902:
The <code>for</code> loop takes either one pattern, for the value, or two, for the key and value; for iterating over keys alone the value may be given an ignore-pattern (<code>_</code>).
 
<langsyntaxhighlight lang="e">def map := [
"a" => 1,
"b" => 2,
Line 484 ⟶ 922:
for key in map.domain() { # iterate over the set whose values are the keys
println(`$key .`)
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
# use array of array for this
clothing$[][] = [ [ "type" "t-shirt" ] [ "color" "red" ] [ "size" "xl" ] ]
for i to len clothing$[][]
print clothing$[i][1] & ": " & clothing$[i][2]
.</syntaxhighlight>
{{out}}
<pre>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'hash) ;; load hash.lib
(define H (make-hash))
;; fill hash table
(hash-set H 'Simon 42)
(hash-set H 'Albert 666)
(hash-set H 'Antoinette 33)
 
;; iterate over (key . value ) pairs
(for ([kv H]) (writeln kv))
(Simon . 42)
(Albert . 666)
(Antoinette . 33)
 
;; iterate over keys
(for ([k (hash-keys H)]) (writeln 'key-> k))
key-> Simon
key-> Albert
key-> Antoinette
 
;; iterate over values
(for ([v (hash-values H)]) (writeln 'value-> v))
value-> 42
value-> 666
value-> 33
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<lang elena>#define system.
#define<syntaxhighlight lang="elena">import system'collections.;
#defineimport system'routines.;
#defineimport extensions.;
public program()
{
// 1. Create
var map := Dictionary.new();
map["key"] := "foox";
map["key"] := "foo";
map["key2"]:= "foo2";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
// Enumerate
map.forEach:
(keyValue){ console.printLine(keyValue.Key," : ",keyValue.Value) }
}</syntaxhighlight>
 
=== Strong typed dictionary ===
// --- Program ---
<syntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
 
#symbolpublic program =()
{
[
// 1. Create
#varauto aMapmap := Dictionary new. Map<string,string>();
aMap@map["key"] := "foox".;
aMap@map["key2key"] := "foo2foo".;
aMap@map["key3key2"]:= "foo3foo2".;
aMap@map["key4key3"]:= "foo4foo3".;
map["key4"]:= "foo4";
 
// Enumerate
map.forEach:
aMap run &each: aKeyValue
[(tuple){ console writeLine:.printLine(aKeyValue key):tuple.Item1," : ":aKeyValue,tuple.Item2) ].}
}</syntaxhighlight>
].</lang>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">IO.inspect d = Map.new([foo: 1, bar: 2, baz: 3])
<lang elixir>defmodule RC do
Enum.each(d, fn kv -> IO.inspect kv end)
def test_iterate(dict_impl \\ Map) do
Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
d = dict_impl.new |> Dict.put(:foo,1) |> Dict.put(:bar,2)
Enum.each(Map.keys(d), fn key -> IO.inspect key end)
print_vals(d)
Enum.each(Map.values(d), fn value -> IO.inspect value end)</syntaxhighlight>
end
defp print_vals(d) do
IO.inspect d
Enum.each(d, fn {k,v} -> IO.puts "#{k}: #{v}" end)
Enum.each(Dict.keys(d), fn key -> IO.inspect key end)
Enum.each(Dict.values(d), fn value -> IO.inspect value end)
end
end
 
IO.puts "< iterate Map >"
RC.test_iterate
IO.puts "\n< iterate HashDict >"
RC.test_iterate(HashDict)</lang>
 
{{out}}
<pre>
%{bar: 2, baz: 3, foo: 1}
< iterate Map >
%{:bar:, 2, foo: 1}
{:baz, 3}
bar: 2
foo{:foo, 1}
:bar => 2
:baz => 3
:foo => 1
:bar
:baz
:foo
2
3
1
</pre>
 
=={{header|EMal}}==
< iterate HashDict >
<syntaxhighlight lang="emal">
#HashDict<[foo: 1, bar: 2]>
Map map = text%text["Italy" => "Rome", "France" => "Paris"]
foo: 1
map.insert("Germany", "Berlin")
bar: 2
map["Spain"] = "Madrid"
:foo
writeLine("== pairs ==")
:bar
for each Pair pair in map
1
writeLine(pair)
2
end
writeLine("== keys ==")
for each text key in map.keys()
writeLine(key)
end
writeLine("== values ==")
for each text value in map.values()
writeLine(value)
end
</syntaxhighlight>
{{out}}
<pre>
== pairs ==
[Italy,Rome]
[France,Paris]
[Germany,Berlin]
[Spain,Madrid]
== keys ==
Italy
France
Germany
Spain
== values ==
Rome
Paris
Berlin
Madrid
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">
-module(assoc).
-compile([export_all]).
Line 564 ⟶ 1,079:
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
end, dict:fetch_keys(D)).
</syntaxhighlight>
</lang>
 
{{out}}
Line 574 ⟶ 1,089:
=={{header|F_Sharp|F#}}==
Iterating over both.
<langsyntaxhighlight lang="fsharp">
let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]
 
for k, v in myMap do
printfn "%s -> %d" k v
</syntaxhighlight>
</lang>
 
Iterating over either keys or values only can be achieved through use of the _ wildcard token.
<langsyntaxhighlight lang="fsharp">
// Only prints the keys.
for k, _ in myMap do
Line 590 ⟶ 1,105:
for _, v in myMap do
printfn "%d" v
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">H{ { "hi" "there" } { "a" "b" } } [ ": " glue print ] assoc-each</langsyntaxhighlight>
<code>assoc-each</code> places both the key and the value on top of the data stack. A simple <code>drop</code> or <code>nip</code> enables iterating over only keys or values.
<syntaxhighlight lang="factor">H{ { "hi" "there" } { "a" "b" } } [ drop print ] assoc-each ! print keys
H{ { "hi" "there" } { "a" "b" } } [ nip print ] assoc-each ! print values</syntaxhighlight>
There's also <code>assoc-map</code>, <code>assoc-find</code>, <code>assoc-filter</code> and many more.
 
Line 600 ⟶ 1,118:
Given a map, <code>each</code> iterates over pairs of values-keys. <code>keys</code> and <code>vals</code> retrieve a list of keys or values, respectively.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 623 ⟶ 1,141:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
{{libheader|Forth Foundation Library}}
 
<langsyntaxhighlight lang="forth">include ffl/hct.fs
include ffl/hci.fs
 
Line 649 ⟶ 1,167:
;
 
iterate</langsyntaxhighlight>
 
<langsyntaxhighlight lang="forth">
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
Line 789 ⟶ 1,307:
 
some-languages kill-association
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 848 ⟶ 1,366:
Ruby invented by: Matsumoto, Yukihiro
count: 10
</pre>
 
=={{header|FreeBASIC}}==
 
Use the typedefs and data from [[Associative Array/Creation#FreeBASIC]] as an include.
 
Since this data structure stores the keys and values together it makes little sense to iterate through the same array three times to print different parts of it, hence I will only print the key:value pairs.
 
<syntaxhighlight lang="freebasic">#include"assoc.bas"
 
function get_dict_data_string( d as dicitem ) as string
select case d.datatype
case BOOL
if d.value.bool then return "true" else return "false"
case INTEG
return str(d.value.integ)
case STRNG
return """"+d.value.strng+""""
case FLOAT
return str(d.value.float)
case BYYTE
return str(d.value.byyte)
case else
return "DATATYPE ERROR"
end select
end function
 
sub print_keyval_pair( d as dicentry )
print using "{&} : {&}";get_dict_data_string( d.key ); get_dict_data_string(d.value)
end sub
 
for i as uinteger = 0 to ubound(Dictionary)
print_keyval_pair(Dictionary(i))
next i</syntaxhighlight>
 
{{out}}
<pre>
{"Cat"} : {"Mittens"}
{32767} : {2.718281828}
</pre>
 
=={{header|Free Pascal}}==
FPC 3.2.0+. Similar to Delphi:<syntaxhighlight lang="pascal">program AssociativeArrayIteration;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses Generics.Collections;
 
type
TlDictionary = TDictionary<string, Integer>;
TlPair = TPair<string,integer>;
 
var
i: Integer;
s: string;
lDictionary: TlDictionary;
lPair: TlPair;
begin
lDictionary := TlDictionary.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSetValue('foo',6);
for lPair in lDictionary do
Writeln('Pair: ',Lpair.Key,' = ',lPair.Value);
for s in lDictionary.Keys do
Writeln('Key: ' + s);
for i in lDictionary.Values do
Writeln('Value: ', i);
finally
lDictionary.Free;
end;
end.</syntaxhighlight>
<pre>
Pair: foo = 6
Pair: bar = 10
Pair: baz = 15
Key: foo
Key: bar
Key: baz
Value: 6
Value: 10
Value: 15</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">d = new dict[[[1, "one"], [2, "two"]]]
for [key, value] = d
println["$key\t$value"]
 
println[]
for key = keys[d]
println["$key"]
</syntaxhighlight>
 
{{out}}
<pre>
2 two
1 one
 
2
1
</pre>
 
=={{header|FutureBasic}}==
There are many ways to iterate over an associative array (dictionary) in FutureBasic. Below are a selection.
 
1. for ... in ...
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFStringRef key
for key in dict
print key, dict[key]
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
2. Enumerator callback
<syntaxhighlight lang="futurebasic">
void local fn MyDictEnumerator( dict as CFDictionaryRef, key as CFTypeRef, obj as CFTypeRef, stp as ^BOOL, userData as ptr )
print key, obj
end fn
 
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
DictionaryEnumerateKeysAndObjects( dict, @fn MyDictEnumerator, NULL )
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
3. Array of keys
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFArrayRef keys = fn DictionaryAllKeys( dict )
CFStringRef key
for key in keys
print key, dict[key]
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
4. Array of values
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFArrayRef values = fn DictionaryAllValues( dict )
CFStringRef value
for value in values
print value
next
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
5. Key/object enumerators
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFStringRef key
CFTypeRef obj
EnumeratorRef keyEnumerator = fn DictionaryKeyEnumerator( dict )
key = fn EnumeratorNextObject( keyEnumerator )
while ( key )
print key,dict[key]
key = fn EnumeratorNextObject( keyEnumerator )
wend
print
EnumeratorRef objectEnumerator = fn DictionaryObjectEnumerator( dict )
obj = fn EnumeratorNextObject( objectEnumerator )
while ( obj )
print obj
obj = fn EnumeratorNextObject( objectEnumerator )
wend
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e48bd6ed7e6b583106b8178bca536eea Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"]
Dim siCount As Short
Dim sTemp As String
 
For Each sTemp In cList
Print cList.key & "=" & sTemp;;
Next
 
Print
 
For siCount = 1 To cList.Count
Print cList[Str(siCount)];;
Next
 
End</syntaxhighlight>
Output:
<pre>
2=quick 4=fox 1=The 9=dog 7=the 5=jumped 3=brown 6=over 8=lazy
The quick brown fox jumped over the lazy dog
</pre>
 
=={{header|Go}}==
'''Language:'''
<lang go>myMap := map[string]int {
<syntaxhighlight lang="go">myMap := map[string]int {
"hello": 13,
"world": 31,
Line 869 ⟶ 1,611:
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}</langsyntaxhighlight>
'''Standard library templates:'''
 
In addition to the for/range features of the language, the text/template and html/template packages of the standard library have map iteration features. Some differences worth noting:
* A single assigned value in a template is the map value. With the language for/range it is the key.
* Templates have no equivalent of _; a dummy variable must be used.
* In a template, if map keys are a comparable basic type, then iteration proceeds in key order. With the language for/range, iteration is in non-deterministic order.
 
<syntaxhighlight lang="go">package main
 
import (
"os"
"text/template"
)
 
func main() {
m := map[string]int{
"hello": 13,
"world": 31,
"!": 71,
}
 
// iterating over key-value pairs:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}, value = {{$v}}
{{end -}}
`)).Execute(os.Stdout, m)
 
// iterating over keys:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}
{{end -}}
`)).Execute(os.Stdout, m)
 
// iterating over values:
template.Must(template.New("").Parse(`
{{- range . -}}
value = {{.}}
{{end -}}
`)).Execute(os.Stdout, m)
}</syntaxhighlight>
{{out}}
Note order by key.
<pre>
key = !, value = 71
key = hello, value = 13
key = world, value = 31
key = !
key = hello
key = world
value = 71
value = 13
value = 31
</pre>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
 
println "Entries:"
Line 884 ⟶ 1,681:
println()
println "Values:"
map.values().each { println it }</langsyntaxhighlight>
 
{{out}}
Line 907 ⟶ 1,704:
24
everywhere</pre>
 
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="visualfoxpro">LOCAL arr := { 6 => 16, "eight" => 8, "eleven" => 11 }
LOCAL x
 
Line 920 ⟶ 1,716:
// or value only
? x
NEXT</langsyntaxhighlight>
 
=={{header|Haskell}}==
with Data.Map:
<langsyntaxhighlight lang="haskell">import qualified Data.Map as M
 
myMap :: M.Map String Int
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]
 
main =:: doIO -- pairs()
main =
print $ M.toList myMap
(putStrLn . unlines) $
-- keys
[ show . M.toList print $ M.keys-- myMapPairs
, show . M.keys -- valuesKeys
, show . M.elems print $ M.elems-- myMap</lang>Values
] <*>
pure myMap</syntaxhighlight>
{{Out}}
<pre>[("!",71),("hello",13),("world",31)]
["!","hello","world"]
[71,13,31]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main()
t := table()
every t[a := !"ABCDE"] := map(a)
Line 950 ⟶ 1,753:
every writes(" ",!t)
write()
end</langsyntaxhighlight>
 
{{out}}
Line 961 ⟶ 1,764:
Keys: C E B D A
Values: c e b d a</pre>
 
=={{header|Io}}==
<syntaxhighlight lang="io">myDict := Map with(
"hello", 13,
"world", 31,
"!" , 71
)
 
// iterating over key-value pairs:
myDict foreach( key, value,
writeln("key = ", key, ", value = ", value)
)
// iterating over keys:
myDict keys foreach( key,
writeln("key = ", key)
)
 
// iterating over values:
myDict foreach( value,
writeln("value = ", value)
)
// or alternatively:
myDict values foreach( value,
writeln("value = ", value)
)</syntaxhighlight>
 
=={{header|J}}==
Line 968 ⟶ 1,797:
Using the J example from [[Creating an Associative Array]]...
 
Keys <syntaxhighlight lang J="j">nl__example 0</langsyntaxhighlight>
 
Values <syntaxhighlight lang J="j">get__example each nl__example 0</langsyntaxhighlight>
 
Both keys and values <langsyntaxhighlight Jlang="j">(,&< get__example) each nl__example 0</langsyntaxhighlight>
 
Note that this last is not likely to be useful in any practical context outside of learning the language.
 
=={{header|JavaJakt}}==
<syntaxhighlight lang="jakt">
<lang java>Map<String, Integer> myDict = new HashMap<String, Integer>();
fn main() {
myDict.put("hello", 1);
let dictionary = ["foo": 1, "bar": 2]
myDict.put("world", 2);
for entry in dictionary {
myDict.put("!", 3);
// To get values, use
// let value = entry.1
println("{}", entry)
}
 
// Just keys
// iterating over key-value pairs:
for key in dictionary.keys() {
for (Map.Entry<String, Integer> e : myDict.entrySet()) {
String key = e.getKey println("{}", key);
}
Integer value = e.getValue();
System.out.println("key = " + key + ", value = " + value);
}
</syntaxhighlight>
{{out}}
<pre>
("bar", 2)
("foo", 1)
bar
foo
</pre>
 
=={{header|Java}}==
// iterating over keys:
<p>
for (String key : myDict.keySet()) {
See also, [https://rosettacode.org/wiki/Associative_array/Creation#Java Java - Associative array/Creation].
System.out.println("key = " + key);
</p>
}
<p>
 
You can access the <kbd>key</kbd> and <kbd>value</kbd> pairs by using the <code>Map.entrySet</code> method,
// iterating over values:
which will return a <code>Map.Entry</code>.<br />
for (Integer value : myDict.values()) {
It's worth noting that a <code>Map.Entry</code> also has the <code>setValue</code> method.
System.out.println("value = " + value);
}</langp>
<syntaxhighlight lang="java">
for (Map.Entry<String, Integer> entry : map.entrySet())
System.out.println(entry);
</syntaxhighlight>
<p>
You can access just the <kbd>key</kbd>s by using the <code>Map.keySet</code> method, which will return a <code>Set</code>.
</p>
<syntaxhighlight lang="java">
for (String key : map.keySet())
System.out.println(key);
</syntaxhighlight>
<p>
And you can access just the <kbd>value</kbd>s by using the <code>Map.values</code> method, which will return a <code>Collection</code>.
</p>
<syntaxhighlight lang="java">
for (int value : map.values())
System.out.println(value);
</syntaxhighlight>
<br />
 
Java 8 version
 
<langsyntaxhighlight lang="java">Map<String, Integer> myDictmap = new HashMap<>();
myDictmap.put("hello", 1);
myDictmap.put("world", 2);
myDictmap.put("!", 3);
 
// iterating over key-value pairs:
myDictmap.forEach((k, v) -> {
System.out.printf("key = %s, value = %s%n", k, v);
});
 
// iterating over keys:
myDictmap.keySet().forEach(k -> System.out.printf("key = %s%n", k));
 
// iterating over values:
myDictmap.values().forEach(v -> System.out.printf("value = %s%n", v));</langsyntaxhighlight>
 
{{out}}
<pre>key = !, value = 3
key = world, value = 2
Line 1,029 ⟶ 1,889:
=={{header|JavaScript}}==
JavaScript does not have associative arrays until ECMAScript 6 brings Maps. In versions up to ES5.1, you may add properties to an empty object to achieve the same effect.
<langsyntaxhighlight lang="javascript">var myhash = {}; //a new, empty object
myhash["hello"] = 3;
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name
Line 1,046 ⟶ 1,906:
keys.map(function (key) {
console.log("Key is: " + key + '. Value is: ' + myhash[key]);
});</langsyntaxhighlight>
 
=={{header|Jq}}==
Line 1,061 ⟶ 1,921:
 
In jq > 1.4, keys_unsorted, for producing an array of the keys (in the order of creation), is also available.
<langsyntaxhighlight lang="jq">def mydict: {"hello":13, "world": 31, "!": 71};
 
# Iterating over the keys
Line 1,092 ⟶ 1,952:
# ["world",31]
# ["!",71]
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
{{transworks with|PythonJulia|0.6}}
<langsyntaxhighlight lang="julia">mydictdict = [ Dict("hello" => 13, "world" => 31, "!" =>71 ]71)
 
# applying a function to key-value pairs:
mapforeach(println, mydictdict);
 
# iterating over key-value pairs:
for (key, value) in mydictdict
println("key = dict[$key, value] = $value")
end
 
# iterating over keys:
for key in keys(mydictdict)
println("key = $@show key")
end
 
# iterating over values:
for value in values(mydictdict)
println("value = $@show value")
end</lang>
</syntaxhighlight>
 
{{out}}
<pre>
Line 1,130 ⟶ 1,992:
=={{header|K}}==
Creating a dictionary.
<langsyntaxhighlight Klang="k"> d: .((`"hello";1); (`"world";2);(`"!";3))</langsyntaxhighlight>
 
The keys are available via "!".
<langsyntaxhighlight Klang="k"> !d
`hello `world `"!"
 
Line 1,139 ⟶ 2,001:
("hello"
"world"
,"!")</langsyntaxhighlight>
 
Print the key value pairs.
<langsyntaxhighlight Klang="k"> `0:{,/$x,": ",d[x]}'!d
hello: 1
world: 2
!: 3</langsyntaxhighlight>
 
The values are available via "[]".
<langsyntaxhighlight Klang="k"> d[]
1 2 3
 
{x+1}'d[]
2 3 4</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main() {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
 
with(map) {
forEach { println("key = ${it.key}, value = ${it.value}") }
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}
}</syntaxhighlight>
{{Out}}
<pre>key = hello, value = 1
key = world, value = 2
key = !, value = 3
key = hello
key = world
key = !
value = 1
value = 2
value = 3</pre>
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: first 0 extract nip ; : second 1 extract nip ; : nip swap drop ;
: say(*) dup first " => " 2 compress "" join . second . ;
 
[['foo 5] ['bar 10] ['baz 20]] 'say apply drop</langsyntaxhighlight>
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
<lang Lasso>
//iterate over associative array
//Lasso maps
Line 1,191 ⟶ 2,074:
//the {^ ^} indicates that output should be printed (AutoCollect) ,
// if output is not desired, just { } is used
</syntaxhighlight>
</lang>
 
=={{header|LFE}}==
 
===Keys and Values===
<langsyntaxhighlight lang="lisp">
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,204 ⟶ 2,087:
0
hash))
</syntaxhighlight>
</lang>
 
===Just Keys===
<langsyntaxhighlight lang="lisp">
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,214 ⟶ 2,097:
(: io format '"~s~n" (list key)))
(: dict fetch_keys hash)))
</syntaxhighlight>
</lang>
 
=={{header|Liberty BASIC}}==
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 "my fave", "220 120 120", "black", "0 0 0"
Line 1,242 ⟶ 2,125:
 
end
</syntaxhighlight>
</lang>
Number of key-data pairs =5
Key 1: red Data: 255 50 50
Line 1,249 ⟶ 2,132:
Key 4: my fave Data: 220 120 120
Key 5: black Data: 0 0 0
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">hash = [#key1:"value1", #key2:"value2", #key3:"value3"]
 
-- iterate over key-value pairs
repeat with i = 1 to hash.count
put hash.getPropAt(i) & "=" & hash[i]
end repeat
 
-- iterating over values only can be written shorter
repeat with val in hash
put val
end repeat</syntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put 3 into fruit["apples"]
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
Line 1,274 ⟶ 2,170:
-- alternatively, use same loop as for values 1 with tkey && fruit[tKey]
 
put tTmp</langsyntaxhighlight>
Output
<langsyntaxhighlight LiveCodelang="livecode">Keys:
apples
pears
Line 1,287 ⟶ 2,183:
bananas:none
oranges:6
pears:5</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">local t = {
["foo"] = "bar",
["baz"] = 6,
Line 1,298 ⟶ 2,194:
for key,val in pairs(t) do
print(string.format("%s: %s", key, val))
end</langsyntaxhighlight>
 
{{out}}
Line 1,307 ⟶ 2,203:
</pre>
''Note:'' the order in which <code>pairs</code> iterates over non-integer keys is not defined, so the order of lines in the output of the above code may differ from one run to another.
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
\\ They use hash function.
\\ Function TwoKeys return Inventory object (as a pointer to object)
Function TwoKeys {
Inventory Alfa="key1":=100, "key2":=200
=Alfa
}
M=TwoKeys()
Print Type$(M)="Inventory"
\\ Normal Use:
\\ Inventories Keys are case sensitive
\\ M2000 identifiers are not case sensitive
Print M("key1"), m("key2")
\\ numeric values can convert to strings
Print M$("key1"), m$("key2")
\\ Iteration
N=Each(M)
While N {
Print Eval(N) ' prints 100, 200 as number
Print M(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N) ' prints 100, 200 as strings
Print M$(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N, N^) ' Prints Keys
}
\\ double iteration
Append M, "key3":=500
N=Each(M, 1, -1) ' start to end
N1=Each(M, -1, 1) ' end to start
\\ 3x3 prints
While N {
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
\\ sort results from lower product to greater product (3+2+1, 6 prints only)
N=Each(M, 1, -1)
While N {
N1=Each(M, N^+1, -1)
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
N=Each(M)
N1=Each(M,-2, 1) ' from second from end to start
\\ print only 2 values. While block ends when one iterator finish
While N, N1 {
Print Eval(N1)*Eval(N)
}
}
Checkit
</syntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
define(`for',
`ifelse($#,0,``$0'',
Line 1,343 ⟶ 2,300:
for(`x',1,asize(`a'),
`avalue(`a',x)
')</langsyntaxhighlight>
 
{{out}}
Line 1,362 ⟶ 2,319:
=={{header|Maple}}==
Iterate through indices when indices are all simple expressions:
<syntaxhighlight lang="maple">
<lang Maple>
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
Line 1,372 ⟶ 2,329:
 
"D"
</syntaxhighlight>
</lang>
 
Iterate through indices when indices may be expression sequences:
<syntaxhighlight lang="maple">
<lang Maple>
> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ):
> for i in indices( T ) do print( i, T[ op( i ) ] ) end:
Line 1,383 ⟶ 2,340:
 
["c", "d"], 3
</syntaxhighlight>
</lang>
 
Return all index / entry pairs as equations:
<syntaxhighlight lang="maple">
<lang Maple>
> for i in indices( T, pairs ) do print( i) end:
"a" = 1
Line 1,393 ⟶ 2,350:
 
("c", "d") = 3
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="maple">
<lang Maple>
> for i in entries( T ) do print( i) end:
[1]
Line 1,402 ⟶ 2,359:
 
[2]
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">keys=DownValues[#,Sort->False][[All,1,1,1]]&;
hashes=#/@keys[#]&;
 
Line 1,412 ⟶ 2,369:
->{2,sometext}
hashes[a]
->{string,23}</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,418 ⟶ 2,375:
Associative arrays can be defined as structs in Matlab and Octave.
 
<langsyntaxhighlight Matlablang="matlab"> keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = getfield(hash,key); % get value of key
hash = setfield(hash,key,-value); % set value of key
end; </langsyntaxhighlight>
 
or
 
<langsyntaxhighlight Matlablang="matlab"> keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = hash.(key); % get value of key
hash.(key) = -value; % set value of key
end; </langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight Maximalang="maxima">h[1]: 6$
h[9]: 2$
 
Line 1,445 ⟶ 2,402:
for key in rest(arrayinfo(h), 2) do (
val: arrayapply(h, key),
print(key, val))$</langsyntaxhighlight>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">d = { 3: "test", "foo": 3 }
 
for keyVal in d
print keyVal // produces results like: { "key": 3, "value": "test" }
end for
 
for key in d.indexes
print key
end for
 
for val in d.values
print val
end for</syntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols
 
Line 1,461 ⟶ 2,433:
loop fn over surname
say fn.right(10) ':' surname[fn]
end fn</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
 
Line 1,475 ⟶ 2,447:
;; loop over the assocation list:
(dolist (elem alist)
(println (format "%s -> %s" (first elem) (last elem))))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">
import tables
 
var t: TTableTable[int,string] = initTable[int,string]()
 
t[1] = "one"
t[2] = "two"
t[3] = "three"
t.add([4,] = "four")
 
echo "t has " & $t.len & " elements"
Line 1,498 ⟶ 2,470:
echo "at[" & $k & "]=" & t[k]
 
#itetateiterate pairs
echo "pair iteration:"
for k,v in t.pairs:
echo "at[" & $k & "]=" & v
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,521 ⟶ 2,493:
 
=={{header|Oberon-2}}==
{{works with|oo2c OO2C|Version 2}}
<syntaxhighlight lang="modula2">
<lang oberon2>
MODULE AssociativeArray;
IMPORT
Line 1,564 ⟶ 2,536:
END AssociativeArray.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Iteration {
function : Main(args : String[]) ~ Nil {
Line 1,593 ⟶ 2,565:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
{{works with|Objective-C|2.0+}}
<langsyntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 1,610 ⟶ 2,582:
for (id value in [myDict objectEnumerator]) {
NSLog(@"value = %@", value);
}</langsyntaxhighlight>
 
{{works with|Objective-C|<2.0}}
<langsyntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 1,630 ⟶ 2,602:
while ((value = [enm nextObject])) {
NSLog(@"value = %@", value);
}</langsyntaxhighlight>
 
{{works with|Cocoa|Mac OS X 10.6+}}
<langsyntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 1,641 ⟶ 2,613:
[myDict enumerateKeysAndObjectsUsingBlock: ^(id key, id value, BOOL *stop) {
NSLog(@"key = %@, value = %@", key, value);
}];</langsyntaxhighlight>
 
=={{header|OCaml}}==
Association array:
<langsyntaxhighlight lang="ocaml">#!/usr/bin/env ocaml
 
let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;
Line 1,659 ⟶ 2,631:
 
(* in functional programming it is often more useful to fold over the elements *)
Array.fold_left (fun acc (k,v) -> acc ^ Printf.sprintf "key: %c - value: %d\n" k v) "Elements:\n" map ;;</langsyntaxhighlight>
 
Hash table:
<langsyntaxhighlight lang="ocaml">let map = Hashtbl.create 42;;
Hashtbl.add map 'A' 1;;
Hashtbl.add map 'B' 2;;
Line 1,671 ⟶ 2,643:
 
(* in functional programming it is often more useful to fold over the elements *)
Hashtbl.fold (fun k v acc -> acc ^ Printf.sprintf "key: %c - value: %d\n" k v) map "Elements:\n" ;;</langsyntaxhighlight>
 
Functional binary search tree:
<langsyntaxhighlight lang="ocaml">module CharMap = Map.Make (Char);;
let map = CharMap.empty;;
let map = CharMap.add 'A' 1 map;;
Line 1,684 ⟶ 2,656:
 
(* in functional programming it is often more useful to fold over the elements *)
CharMap.fold (fun k v acc -> acc ^ Printf.sprintf "key: %c - value: %d\n" k v) map "Elements:\n" ;;</langsyntaxhighlight>
 
=={{header|Ol}}==
<syntaxhighlight lang="ol">
;;; create sample associative array
(define aa (list->ff '(
(hello . 1)
(world . 2)
(! . 3))))
 
(print aa)
; ==> #((! . 3) (hello . 1) (world . 2))
 
;;; simplest iteration over all associative array (using ff-iter, lazy iterator)
(let loop ((kv (ff-iter aa)))
(cond
((null? kv) #true)
((pair? kv)
(print (car kv))
(loop (cdr kv)))
(else (loop (force kv)))))
; ==> (! . 3)
; ==> (hello . 1)
; ==> (world . 2)
 
;;; iteration with returning value (using ff-fold)
(print
"folding result: "
(ff-fold
(lambda (result key value)
(print "key: " key ", value: " value)
(+ result 1))
0
aa))
 
; ==> key: !, value: 3
; ==> key: hello, value: 1
; ==> key: world, value: 2
; ==> folding result: 3
 
;;; same but right fold (using ff-foldr)
(print
"rfolding result: "
(ff-foldr
(lambda (result key value)
(print "key: " key ", value: " value)
(+ result 1))
0
aa))
 
; ==> key: world, value: 2
; ==> key: hello, value: 1
; ==> key: !, value: 3
; ==> rfolding result: 3
 
;;; at least create new array from existing (let's multiply every value by value)
(define bb (ff-map aa
(lambda (key value)
(* value value))))
(print bb)
 
; ==> #((! . 9) (hello . 1) (world . 4))
 
</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">d = .directory~new
<lang oorexx>
d = .directory~new
d["hello"] = 1
d["world"] = 2
Line 1,708 ⟶ 2,742:
say "key =" s~index", value =" s~item
s~next
end</syntaxhighlight>
end
{{out}}
</lang>
<pre>key = !
key = world
key = hello
value = 3
value = 2
value = 1
key = !, value = 3
key = world, value = 2
key = hello, value = 1</pre>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
MyMap = unit('hello':13 'world':31 '!':71)
in
{ForAll {Record.toListInd MyMap} Show} %% pairs
{ForAll {Record.arity MyMap} Show} %% keys
{ForAll {Record.toList MyMap} Show} %% values</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,723 ⟶ 2,766:
 
The keys can be retried from a map with Vec:
<langsyntaxhighlight lang="parigp">keys = Vec(M);</langsyntaxhighlight>
You can iterate over the values as usual:
<langsyntaxhighlight lang="parigp">for(i=1,#keys,
print(keys[i]," ",mapget(M,keys[i]))
)</langsyntaxhighlight>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
begin
var zoo := new Dictionary<string,integer>;
zoo['crocodile'] := 2;
zoo['jiraffe'] := 3;
zoo['behemoth'] := 1;
foreach var kv in zoo do
Println(kv.Key, kv.Value);
Println;
foreach var key in zoo.Keys do
Println(key,zoo[key]);
end.
</syntaxhighlight>
{{out}}
<pre>
crocodile 2
jiraffe 3
behemoth 1
 
crocodile 2
jiraffe 3
behemoth 1
</pre>
 
 
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#! /usr/bin/perl
use strict;
 
Line 1,761 ⟶ 2,831:
foreach my $val ( values %pairs ) {
print "value = $val\n";
}</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
The first three lines create a simple dictionary, with keys and values of several different types (string/integer/sequence):
{{works with|Rakudo|#21 "Seattle"}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang perl6>my %pairs = hello => 13, world => 31, '!' => 71;
<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: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"duo"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">({</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"six"</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">visitor</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000080;font-style:italic;">/*userdata*/</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- (continue traversal)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"visitor"</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{2,"duo"}
{{3,4},{5,"six"}}
{"one",1}
</pre>
You could also use some of the map.e routines:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"duo"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">({</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"six"</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (map.e incompatible with p2js before that)</span>
for %pairs.kv -> $k, $v {
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">map</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
say "(k,v) = ($k, $v)";
<span style="color: #0000FF;">?</span><span style="color: #000000;">pairs</span><span style="color: #0000FF;">()</span>
}
<span style="color: #0000FF;">?</span><span style="color: #000000;">keys</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">values</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{{2,"duo"},{{3,4},{5,"six"}},{"one",1}}
{2,{3,4},"one"}
{"duo",{5,"six"},1}
</pre>
 
=={{header|Phixmonti}}==
{ say "$^a => $^b" } for %pairs.kv;
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
def getd /# dict key -- dict data #/
say "key = $_" for %pairs.keys;
swap 1 get rot find nip
dup if
swap 2 get rot get nip
else
drop "Unfound"
endif
enddef
 
 
say "value = $_" for %pairs.values;</lang>
def setd /# dict ( key data ) -- dict #/
1 get var ikey
2 get var idata
drop
1 get ikey find var p drop
p if
2 get idata p set 2 set
else
2 get idata 0 put 2 set
1 get ikey 0 put 1 set
endif
enddef
 
 
def pair /# dict n -- dict ( k d ) #/
1 over 2 tolist var ikey
2 swap 2 tolist var idata
ikey sget
swap idata sget rot swap
2 tolist
enddef
 
def scandict /# dict n -- dict ( ) #/
var n
1 get len nip
for
pair
n if n get nip endif
print nl
endfor
enddef
 
def pairs /# dict -- dict ( ) #/
0 scandict
enddef
 
def keys
1 scandict
enddef
 
def values
2 scandict
enddef
 
/# ---------- MAIN ---------- #/
 
( ( ) ( ) )
 
( "one" 1 ) setd
( 2 "duo" ) setd
( ( 3 4 ) ( 5 "six" ) ) setd
 
pairs nl
keys nl
values
</syntaxhighlight>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$pairs = array( "hello" => 1,
"world" => 2,
Line 1,798 ⟶ 2,963:
echo "values = $value\n";
}
?></langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
Map = new_map([1=one,2=two,3=three,4=four]),
foreach(K=V in Map)
println(K=V)
end,
nl,
 
println(keys=Map.keys),
foreach(K in Map.keys.sort)
println(K=Map.get(K))
end,
nl,
 
println(values=Map.values),
foreach(V in Map.values.sort)
% This works but gets a warning: nonlocal_var_in_iterator_pattern
% println(V=[K : K=V in Map])
% No warning:
println(V=[K : K=V1 in Map,V1 == V])
end,
nl.</syntaxhighlight>
 
{{out}}
<pre>1 = one
2 = two
3 = three
4 = four
 
keys = [1,2,3,4]
1 = one
2 = two
3 = three
4 = four
 
values = [one,two,three,four]
four = [4]
one = [1]
three = [3]
two = [2]</pre>
 
 
=={{header|PicoLisp}}==
===Using properties===
<langsyntaxhighlight PicoLisplang="picolisp">(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
Line 1,813 ⟶ 3,021:
 
: (mapcar car (getl 'A)) # Get all values
-> (15 10 5)</langsyntaxhighlight>
===Using an index tree===
<langsyntaxhighlight PicoLisplang="picolisp">(idx 'A (def "foo" 5) T)
(idx 'A (def "bar" 10) T)
(idx 'A (def "baz" 15) T)
Line 1,826 ⟶ 3,034:
 
: (mapcar val (idx 'A)) # Get all values
-> (10 15 5)</langsyntaxhighlight>
 
=={{header|Pike}}==
Line 1,832 ⟶ 3,040:
the order is deterministic however.
 
<syntaxhighlight lang="pike">
<lang Pike>
mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]);
foreach(m; string key; string value)
Line 1,854 ⟶ 3,062:
Result: bac
 
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
<langsyntaxhighlight lang="postscript">
% over keys and values
<</a 1 /b 2 /c 3>> {= =} forall
Line 1,864 ⟶ 3,072:
% just values
<</a 1 /b 2 /c 3>> {pop =} forall
</syntaxhighlight>
</lang>
 
=={{header|Potion}}==
We can traverse tables by key or by key and val. We cannot traverse tables only by val.
<syntaxhighlight lang="potion">mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)
 
mydictionary each (key, val): (key, ":", val, "\n") join print.
mydictionary each (key): (key, "\n") join print.</syntaxhighlight>
 
=={{header|PowerShell}}==
Using the following hash table:
<langsyntaxhighlight lang="powershell">$h = @{ 'a' = 1; 'b' = 2; 'c' = 3 }</langsyntaxhighlight>
Iterating over the key/value pairs is slightly cumbersome as it requires an explicit call to <code>GetEnumerator</code>:
<langsyntaxhighlight lang="powershell">$h.GetEnumerator() | ForEach-Object { Write-Host Key: $_.Name, Value: $_.Value }</langsyntaxhighlight>
A <code>foreach</code> statement can also be used:
<langsyntaxhighlight lang="powershell">foreach ($e in $h.GetEnumerator()) {
Write-Host Key: $e.Name, Value: $e.Value
}</langsyntaxhighlight>
Iterating over the keys:
<langsyntaxhighlight lang="powershell">$h.Keys | ForEach-Object { Write-Host Key: $_ }
 
foreach ($k in $h.Keys) {
Write-Host Key: $k
}</langsyntaxhighlight>
Iterating over the values:
<langsyntaxhighlight lang="powershell">$h.Values | ForEach-Object { Write-Host Value: $_ }
 
foreach ($v in $h.Values) {
Write-Host Value: $v
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
Line 1,893 ⟶ 3,108:
from having more than one value):
 
<langsyntaxhighlight lang="prolog">
assert( mymap(key1,value1) ).
assert( mymap(key2,value1) ).
</syntaxhighlight>
</lang>
 
To perform the specific task at hand:
<langsyntaxhighlight lang="prolog">
?- forall( mymap(Key,Value), writeln( [Key,Value]) ).
 
[key1,value1]
[key2,value1]
</syntaxhighlight>
</lang>
 
In Prolog, however, iteration is "built-in". For example:
<langsyntaxhighlight lang="prolog">
?- mymap(key1, Y).
Y = value1.
Line 1,914 ⟶ 3,129:
X = key1 ;
X = key2.
</syntaxhighlight>
</lang>
 
To construct the list of keys:
<langsyntaxhighlight lang="prolog">
?- findall( X, mymap(X,value1), Xs).
Xs = [key1, key2].
</syntaxhighlight>
</lang>
 
To construct the list of distinct values:
<langsyntaxhighlight lang="prolog">
?- findall( Y, mymap(key1,Y), Ys).
Ys = [value1].
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
Hashes are a built-in type called Map in Purebasic.
 
<langsyntaxhighlight lang="purebasic">NewMap dict.s()
dict("de") = "German"
dict("en") = "English"
Line 1,938 ⟶ 3,153:
ForEach dict()
Debug MapKey(dict()) + ":" + dict()
Next</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">myDict = { "hello": 13,
"world": 31,
"!" : 71 }
Line 1,958 ⟶ 3,173:
# iterating over values:
for value in myDict.values():
print ("value = %s" % value)</langsyntaxhighlight>
 
=={{header|QB64}}==
<syntaxhighlight lang="qb64">
'dictionary is not native data type of QB64
' here a dictionary engine using a string to store data
Dim Shared Skey As String * 1, SValue As String * 1, EValue As String * 1
Skey = Chr$(0)
SValue = Chr$(1)
EValue = Chr$(255)
'Demo area---------------->
Dim MyDictionary As String
If ChangeValue(MyDictionary, "a", "Ananas") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "b", "Banana") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "c", "cherry") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "d", "Drake") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "e", "Elm") Then Print "added new couple key value"
If ChangeValue(MyDictionary, "f", "Fire") Then Print "added new couple key value"
Print LenDict(MyDictionary)
Print "to key e there is "; GetDict$(MyDictionary, "e")
Print "to key e there is "; GetDict$(MyDictionary, "a")
If ChangeValue(MyDictionary, "e", "Elephant") Then Print " changed value of key passed"
Print "to key e there is "; GetDict$(MyDictionary, "e")
If Not (EraseKeyValue(MyDictionary, "e")) Then Print " Failed to erase key value passed" Else Print "Erased key value passed"
If GetDict$(MyDictionary, "e") = "" Then Print " No couple key value found for key value 'e'"
If ChangeKey(MyDictionary, "e", "f") = 0 Then
Print "key -a- has value "; GetDict$(MyDictionary, "a")
Print "we change key a to key e "
If ChangeKey(MyDictionary, "a", "e") = -1 Then
Print "key -a- has value "; GetDict$(MyDictionary, "a")
Print "key -e- has value "; GetDict$(MyDictionary, "e")
End If
End If
If InsertCouple(MyDictionary, "c", "m", "mellon") = -1 Then
Print " New couple inserted after key -c- "; GetDict$(MyDictionary, "c")
Print " new couple is key -m- "; GetDict$(MyDictionary, "m")
End If
Print LenDict(MyDictionary)
' End demo area --------------->
End
' it returns value/s for a key
Function GetDict$ (dict As String, Keys As String)
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then GetDict$ = "" Else GetDict = Mid$(dict, StartV + 1, EndV - StartV)
End Function
' it changes value of a key or append the couple key, newvalue if key is new
Function ChangeValue (dict As String, Keys As String, NewValue As String)
ChangeValue = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
dict = dict + Skey + Keys + SValue + NewValue + EValue
Else
dict = Left$(dict, StartV) + NewValue + Right$(dict, Len(dict) - EndV + 1)
End If
ChangeValue = -1
End Function
'it changes a key if it is in the dictionary
Function ChangeKey (dict As String, Keys As String, NewKey As String)
ChangeKey = 0
Dim StartK As Integer, StartV As Integer
StartK = InStr(dict, Skey + Keys + SValue)
StartV = InStr(StartK, dict, SValue)
If StartK = 0 Then
Print "Key " + Keys + " not found"
Exit Function
Else
dict = Left$(dict, StartK) + NewKey + Right$(dict, Len(dict) - StartV + 1)
End If
ChangeKey = -1
End Function
'it erases the couple key value
Function EraseKeyValue (dict As String, keys As String)
EraseKeyValue = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + keys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
Exit Function
Else
dict = Left$(dict, StartK - 1) + Right$(dict, Len(dict) - EndV + 1)
End If
EraseKeyValue = -1
End Function
'it inserts a couple after a defined key, if key is not in dictionary it append couple key value
Function InsertCouple (dict As String, SKeys As String, Keys As String, Value As String)
InsertCouple = 0
Dim StartK As Integer, StartV As Integer, EndV As Integer
StartK = InStr(dict, Skey + SKeys + SValue)
StartV = InStr(StartK, dict, SValue)
EndV = InStr(StartV, dict, EValue)
If StartK = 0 Then
dict = dict + Skey + Keys + SValue + Value + EValue
Else
dict = Left$(dict, EndV) + Skey + Keys + SValue + Value + EValue + Right$(dict, Len(dict) - EndV + 1)
End If
InsertCouple = -1
End Function
Function LenDict (dict As String)
LenDict = 0
Dim a As Integer, count As Integer
If Len(dict) <= 0 Then Exit Function
While a <= Len(dict)
a = InStr(a + 1, dict, EValue)
If a > 0 Then count = count + 1 Else Exit While
Wend
LenDict = count
End Function
 
</syntaxhighlight>
=={{header|R}}==
 
Line 1,966 ⟶ 3,304:
=== environment example ===
 
<langsyntaxhighlight lang="r">> env <- new.env()
> env[["x"]] <- 123
> env[["x"]]</langsyntaxhighlight>
<pre>[1] 123</pre>
<langsyntaxhighlight lang="r">> index <- "1"
> env[[index]] <- "rainfed hay"
> for (name in ls(env)) {
+ cat(sprintf('index=%s, value=%s\n', name, env[[name]]))
+ }</langsyntaxhighlight>
<pre>index=1, value=rainfed hay
index=x, value=123</pre>
Line 1,980 ⟶ 3,318:
=== vector example ===
 
<langsyntaxhighlight lang="r">> x <- c(hello=1, world=2, "!"=3)
> print(x["!"])</langsyntaxhighlight>
<pre>!
3</pre>
<langsyntaxhighlight lang="r">> print(unname(x["!"]))</langsyntaxhighlight>
<pre>[1] 3</pre>
 
=== list example ===
 
<langsyntaxhighlight Rlang="r">> a <- list(a=1, b=2, c=3.14, d="xyz")
> print(a$a)</langsyntaxhighlight>
<pre>[1] 1</pre>
<syntaxhighlight lang R="r">> print(a$d)</langsyntaxhighlight>
<pre>[1] "xyz"</pre>
 
Line 1,998 ⟶ 3,336:
Using the dictionary interface, different data structures can be treated as an associative array in Racket.
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 2,009 ⟶ 3,347:
(for/list ([(k v) (in-dict dict3)]) ; => '("0 -> a" "1 -> b" "2 -> c")
(format "~a -> ~a" k v))
</syntaxhighlight>
</lang>
 
=={{header|REXXRaku}}==
(formerly Perl 6)
<lang rexx>/*REXX program shows how to set/display values for an associative array.*/
{{works with|Rakudo|2015.12}}
/*┌────────────────────────────────────────────────────────────────────┐
│ The (below) two REXX statements aren't really necessary, but it │
│ shows how to define any and all entries in a associative array so │
│ that if a "key" is used that isn't defined, it can be displayed to │
│ indicate such, or its value can be checked to determine if a │
│ particular associative array element has been set (defined). │
└────────────────────────────────────────────────────────────────────┘*/
stateF.=' [not defined yet] ' /*sets any/all state former caps.*/
stateN.=' [not defined yet] ' /*sets any/all state names. */
/*┌────────────────────────────────────────────────────────────────────┐
│ In REXX, when a "key" is used, it's normally stored (internally) │
│ as uppercase characters (as in the examples below). Actually, any │
│ characters can be used, including blank(s) and non-displayable │
│ characters (including '00'x, 'ff'x, commas, periods, quotes, ···).│
└────────────────────────────────────────────────────────────────────┘*/
stateL='' /*list of states (empty now). It's nice to be in alpha-*/
/*betic order; they'll be listed in this order. With a */
/*little more code, they could be sorted quite easily. */
 
<syntaxhighlight lang="raku" line>my %pairs = hello => 13, world => 31, '!' => 71;
call setSC 'al', "Alabama" ,'Tuscaloosa'
call setSC 'ca', "California" ,'Benicia'
for %pairs.kv -> $k, $v {
call setSC 'co', "Colorado" ,'Denver City'
say "(k,v) = ($k, $v)";
call setSC 'ct', "Connecticut" ,'Hartford and New Haven (joint)'
}
call setSC 'de', "Delaware" ,'New-Castle'
call setSC 'ga', "Georgia" ,'Milledgeville'
call setSC 'il', "Illinois" ,'Vandalia'
call setSC 'in', "Indiana" ,'Corydon'
call setSC 'ia', "Iowa" ,'Iowa City'
call setSC 'la', "Louisiana" ,'New Orleans'
call setSC 'me', "Maine" ,'Portland'
call setSC 'mi', "Michigan" ,'Detroit'
call setSC 'ms', "Mississippi" ,'Natchez'
call setSC 'mo', "Missoura" ,'Saint Charles'
call setSC 'mt', "Montana" ,'Virginia City'
call setSC 'ne', "Nebraska" ,'Lancaster'
call setSC 'nh', "New Hampshire" ,'Exeter'
call setSC 'ny', "New York" ,'New York'
call setSC 'nc', "North Carolina" ,'Fayetteville'
call setSC 'oh', "Ohio" ,'Chillicothe'
call setSC 'ok', "Oklahoma" ,'Guthrie'
call setSC 'pa', "Pennsylvania" ,'Lancaster'
call setSC 'sc', "South Carolina" ,'Charlestown'
call setSC 'tn', "Tennessee" ,'Murfreesboro'
call setSC 'vt', "Vermont" ,'Windsor'
 
# Stable order
do j=1 for words(stateL) /*show all capitals that were set*/
for %pairs.sort(*.value)>>.kv -> ($k, $v) {
q=word(stateL,j) /*get the next state in the list.*/
say "(k,v) = ($k, $v)";
say 'the former capital of ('q") " stateN.q " was " stateC.q
}
end /*j*/ /* [↑] display states defined. */
 
exit /*stick a fork in it, we're done.*/
{ say "$^a => $^b" } for %pairs.kv;
/*─────────────────────────────────────setSC subroutine─────────────────*/
 
setSC: arg code; parse arg ,name,cap /*get upper code, get name & cap.*/
say "key = $_" for %pairs.keys;
stateL=stateL code /*keep a list of all state codes.*/
 
stateN.code=name /*set the state's name. */
say "value = $_" for %pairs.values;</syntaxhighlight>
stateC.code=cap /*set the state's capital. */
 
return /*return to invoker, SET is done.*/</lang>
=={{outheader|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program demonstrates how to set and display values for an associative array. */
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║ The (below) two REXX statements aren't really necessary, but it shows how to ║
║ define any and all entries in a associative array so that if a "key" is used that ║
║ isn't defined, it can be displayed to indicate such, or its value can be checked ║
║ to determine if a particular associative array element has been set (defined). ║
╚════════════════════════════════════════════════════════════════════════════════════╝*/
stateF.= ' [not defined yet] ' /*sets any/all state former capitals.*/
stateN.= ' [not defined yet] ' /*sets any/all state names. */
w = 0 /*the maximum length of a state name.*/
stateL =
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║ The list of states (empty as of now). It's convenient to have them in alphabetic ║
║ order; they'll be listed in the order as they are in the REXX program below). ║
║ In REXX, when a key is used (for a stemmed array, as they are called in REXX), ║
║ and the key isn't assigned a value, the key's name is stored (internally) as ║
║ uppercase (Latin) characters (as in the examples below. If the key has a ║
║ a value, the key's value is used as is (i.e.: no upper translation is performed).║
║ Actually, any characters can be used, including blank(s) and non─displayable ║
║ characters (including '00'x, 'ff'x, commas, periods, quotes, ···). ║
╚════════════════════════════════════════════════════════════════════════════════════╝*/
call setSC 'al', "Alabama" , 'Tuscaloosa'
call setSC 'ca', "California" , 'Benicia'
call setSC 'co', "Colorado" , 'Denver City'
call setSC 'ct', "Connecticut" , 'Hartford and New Haven (jointly)'
call setSC 'de', "Delaware" , 'New-Castle'
call setSC 'ga', "Georgia" , 'Milledgeville'
call setSC 'il', "Illinois" , 'Vandalia'
call setSC 'in', "Indiana" , 'Corydon'
call setSC 'ia', "Iowa" , 'Iowa City'
call setSC 'la', "Louisiana" , 'New Orleans'
call setSC 'me', "Maine" , 'Portland'
call setSC 'mi', "Michigan" , 'Detroit'
call setSC 'ms', "Mississippi" , 'Natchez'
call setSC 'mo', "Missouri" , 'Saint Charles'
call setSC 'mt', "Montana" , 'Virginia City'
call setSC 'ne', "Nebraska" , 'Lancaster'
call setSC 'nh', "New Hampshire" , 'Exeter'
call setSC 'ny', "New York" , 'New York'
call setSC 'nc', "North Carolina" , 'Fayetteville'
call setSC 'oh', "Ohio" , 'Chillicothe'
call setSC 'ok', "Oklahoma" , 'Guthrie'
call setSC 'pa', "Pennsylvania" , 'Lancaster'
call setSC 'sc', "South Carolina" , 'Charlestown'
call setSC 'tn', "Tennessee" , 'Murfreesboro'
call setSC 'vt', "Vermont" , 'Windsor'
 
do j=1 for words(stateL) /*show all capitals that were defined. */
$= word(stateL, j) /*get the next (USA) state in the list.*/
say 'the former capital of ('$") " left(stateN.$, w) " was " stateC.$
end /*j*/ /* [↑] show states that were defined.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
setSC: parse arg code,name,cap; upper code /*get code, name & cap.; uppercase code*/
stateL= stateL code /*keep a list of all the US state codes*/
stateN.code= name; w= max(w,length(name)) /*define the state's name; max width. */
stateC.code= cap /* " " " code to the capital*/
return /*return to invoker, SETSC is finished.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default input:}}
<pre>
the former capital of (AL) Alabama was Tuscaloosa
the former capital of (CA) California was Benicia
the former capital of (CO) Colorado was Denver City
the former capital of (CT) Connecticut was Hartford and New Haven (jointjointly)
the former capital of (DE) Delaware was New-Castle
the former capital of (GA) Georgia was Milledgeville
the former capital of (IL) Illinois was Vandalia
the former capital of (IN) Indiana was Corydon
the former capital of (IA) Iowa was Iowa City
the former capital of (LA) Louisiana was New Orleans
the former capital of (ME) Maine was Portland
the former capital of (MI) Michigan was Detroit
the former capital of (MS) Mississippi was Natchez
the former capital of (MO) MissouraMissouri was Saint Charles
the former capital of (MT) Montana was Virginia City
the former capital of (NE) Nebraska was Lancaster
the former capital of (NH) New Hampshire was Exeter
the former capital of (NY) New York was New York
the former capital of (NC) North Carolina was Fayetteville
the former capital of (OH) Ohio was Chillicothe
the former capital of (OK) Oklahoma was Guthrie
the former capital of (PA) Pennsylvania was Lancaster
the former capital of (SC) South Carolina was Charlestown
the former capital of (TN) Tennessee was Murfreesboro
the former capital of (VT) Vermont was Windsor
</pre>
When this example was started, the intention was to list the former capitals by key. &nbsp; Unfortunately, there's a duplicate capital &nbsp; (Lancaster).
<br><br>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Associative array/Iteration
 
lst = [["hello", 13], ["world", 31], ["!", 71]]
for n = 1 to len(lst)
see lst[n][1] + " : " + lst[n][2] + nl
next
</syntaxhighlight>
Output:
<pre>
hello : 13
world : 31
! : 71
</pre>
 
=={{header|RLaB}}==
Associative arrays are called ''lists'' in RLaB.
 
<syntaxhighlight lang="rlab">
<lang RLaB>
x = <<>>; // create an empty list
x.hello = 1;
Line 2,128 ⟶ 3,504:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">myDictmy_dict = { "hello" => 13,
"world" => 31,
"!" => 71 }
 
# iterating over key-value pairs:
myDictmy_dict.each {|key, value| puts "key = #{key}, value = #{value}"}
# or
myDictmy_dict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}
 
# iterating over keys:
myDictmy_dict.each_key {|key| puts "key = #{key}"}
 
# iterating over values:
myDictmy_dict.each_value {|value| puts "value =#{value}"}</langsyntaxhighlight>
 
another way:
<langsyntaxhighlight lang="ruby">for key, value in myDictmy_dict
puts "key = #{key}, value = #{value}"
end
 
for key in myDictmy_dict.keys
puts "key = #{key}"
end
 
for value in myDictmy_dict.values
puts "value = #{value}"
end</langsyntaxhighlight>
 
{{out}}
Line 2,173 ⟶ 3,549:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
Line 2,185 ⟶ 3,561:
}
}</langsyntaxhighlight>
{{out}}
Note that <code>HashMap</code> does not preserve order (if this is important, <code>std::collections::BTreeMap</code> is what you want.)
Line 2,196 ⟶ 3,572:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
 
println(f"Key->Value: ${m.mkString(", ")}%s")
Line 2,202 ⟶ 3,578:
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s")</langsyntaxhighlight>{{out}}<pre>
Key->Value: Amsterdam -> Netherlands, New York -> USA, Heemstede -> Netherlands
Pairs: (Amsterdam,Netherlands), (New York,USA), (Heemstede,Netherlands)
Line 2,209 ⟶ 3,585:
Unique values: Netherlands, USA
</pre>
 
 
=={{header|Scheme}}==
Line 2,215 ⟶ 3,590:
{{works with|Gauche Scheme}}
 
<syntaxhighlight lang="scheme">
<lang Scheme>
;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
Line 2,226 ⟶ 3,601:
;; Create by "partial application" a function that accepts 2 arguments,
;; the key and the value:
(pa$ format #t "Key = ~a, Value = ~a\n"))</langsyntaxhighlight>
 
Output:
Line 2,235 ⟶ 3,610:
</pre>
 
<syntaxhighlight lang="scheme">
<lang Scheme>
;; Iterate over the table and create a list of the keys and the
;; altered values:
Line 2,247 ⟶ 3,622:
(lambda (k-v) (cons (car k-v) (+ (cdr k-v) 5000)))
table)
</syntaxhighlight>
</lang>
 
To get a list of the keys or of the values of the table,
Line 2,256 ⟶ 3,631:
(hash-table-values table)
</pre>
 
=== For [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] ===
{{works with|CHICKEN|5.3.0}}
{{libheader|r7rs}}
{{libheader|srfi-1}}
 
Here is a variant of [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] that includes ''generators''. Such generators are functionally equivalent to iterators; the only important difference is they are executable procedures rather than passive objects. Note also that, because these associative arrays are persistent, iterating through their structure is much safer than it would be in a conventional hash table, which might change or even disappear while you were doing the iteration.
 
What I present here is a trimmed-down version of what you might find in a prefabricated library, such as an implementation of SRFI-125. I suppose part of my point in presenting this is that ‘associative arrays’ are not actually part of the Scheme language (even in R6RS), but rather are library add-ons. Someone else has done the sort of thing I am demonstrating here. This is in contrast to, say, Awk, or Icon, where associative ‘arrays’ ''really are'' built into the language.
 
(To save space, I have removed comments you can read at the section for [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]].)
 
<syntaxhighlight lang="scheme">(cond-expand
(r7rs)
(chicken (import r7rs)))
 
(define-library (suspendable-procedures)
 
(export &fail failure? success? suspend fail-forever
make-generator-procedure)
 
(import (scheme base))
 
(begin
 
(define-record-type <&fail>
(make-the-one-unique-&fail-that-you-must-not-make-twice)
do-not-use-this:&fail?)
 
(define &fail
(make-the-one-unique-&fail-that-you-must-not-make-twice))
 
(define (failure? f) (eq? f &fail))
(define (success? f) (not (failure? f)))
(define *suspend* (make-parameter (lambda (x) x)))
(define (suspend v) ((*suspend*) v))
(define (fail-forever)
(let loop ()
(suspend &fail)
(loop)))
 
(define (make-generator-procedure thunk)
;; This is for making a suspendable procedure that takes no
;; arguments when resumed. The result is a simple generator of
;; values.
(define (next-run return)
(define (my-suspend v)
(set! return (call/cc (lambda (resumption-point)
(set! next-run resumption-point)
(return v)))))
(parameterize ((*suspend* my-suspend))
(suspend (thunk))
(fail-forever)))
(lambda () (call/cc next-run)))
 
)) ;; end library (suspendable-procedures)
 
(define-library (avl-trees)
;;
;; Persistent (that is, ‘immutable’) AVL trees for R7RS Scheme.
;;
;; References:
;;
;; * Niklaus Wirth, 1976. Algorithms + Data Structures =
;; Programs. Prentice-Hall, Englewood Cliffs, New Jersey.
;;
;; * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated
;; by Fyodor Tkachov, 2014.
;;
 
(export avl-make-generator)
(export avl avl? avl-empty? avl-insert avl-search-values)
(export avl-check-usage)
 
(import (scheme base))
(import (scheme case-lambda))
(import (scheme process-context))
(import (scheme write))
(import (suspendable-procedures))
 
(begin
 
(define-syntax avl-check-usage
(syntax-rules ()
((_ pred msg)
(or pred (usage-error msg)))))
 
(define-record-type <avl>
(%avl key data bal left right)
avl?
(key %key)
(data %data)
(bal %bal)
(left %left)
(right %right))
 
(define avl-make-generator
(case-lambda
((tree) (avl-make-generator tree 1))
((tree direction)
(if (negative? direction)
(make-generator-procedure
(lambda ()
(define (traverse p)
(unless (or (not p) (avl-empty? p))
(traverse (%right p))
(suspend (cons (%key p) (%data p)))
(traverse (%left p)))
&fail)
(traverse tree)))
(make-generator-procedure
(lambda ()
(define (traverse p)
(unless (or (not p) (avl-empty? p))
(traverse (%left p))
(suspend (cons (%key p) (%data p)))
(traverse (%right p)))
&fail)
(traverse tree)))))))
 
(define (avl) (%avl #f #f #f #f #f))
 
(define (avl-empty? tree)
(avl-check-usage
(avl? tree)
"avl-empty? expects an AVL tree as argument")
(not (%bal tree)))
 
(define (avl-search-values pred<? tree key)
(define (search p)
(if (not p)
(values #f #f)
(let ((k (%key p)))
(cond ((pred<? key k) (search (%left p)))
((pred<? k key) (search (%right p)))
(else (values (%data p) #t))))))
(avl-check-usage
(procedure? pred<?)
"avl-search-values expects a procedure as first argument")
(if (avl-empty? tree)
(values #f #f)
(search tree)))
 
(define (avl-insert pred<? tree key data)
(define (search p fix-balance?)
(cond
((not p)
(values (%avl key data 0 #f #f) #t))
((pred<? key (%key p))
(let-values (((p1 fix-balance?)
(search (%left p) fix-balance?)))
(cond
((not fix-balance?)
(let ((p^ (%avl (%key p) (%data p) (%bal p)
p1 (%right p))))
(values p^ #f)))
(else
(case (%bal p)
((1)
(let ((p^ (%avl (%key p) (%data p) 0
p1 (%right p))))
(values p^ #f)))
((0)
(let ((p^ (%avl (%key p) (%data p) -1
p1 (%right p))))
(values p^ fix-balance?)))
((-1)
(case (%bal p1)
((-1)
(let* ((p^ (%avl (%key p) (%data p) 0
(%right p1) (%right p)))
(p1^ (%avl (%key p1) (%data p1) 0
(%left p1) p^)))
(values p1^ #f)))
((0 1)
(let* ((p2 (%right p1))
(bal2 (%bal p2))
(p^ (%avl (%key p) (%data p)
(- (min bal2 0))
(%right p2) (%right p)))
(p1^ (%avl (%key p1) (%data p1)
(- (max bal2 0))
(%left p1) (%left p2)))
(p2^ (%avl (%key p2) (%data p2) 0
p1^ p^)))
(values p2^ #f)))
(else (internal-error))))
(else (internal-error)))))))
 
((pred<? (%key p) key)
(let-values (((p1 fix-balance?)
(search (%right p) fix-balance?)))
(cond
((not fix-balance?)
(let ((p^ (%avl (%key p) (%data p) (%bal p)
(%left p) p1)))
(values p^ #f)))
(else
(case (%bal p)
((-1)
(let ((p^ (%avl (%key p) (%data p) 0
(%left p) p1)))
(values p^ #f)))
((0)
(let ((p^ (%avl (%key p) (%data p) 1
(%left p) p1)))
(values p^ fix-balance?)))
((1)
(case (%bal p1)
((1)
(let* ((p^ (%avl (%key p) (%data p) 0
(%left p) (%left p1)))
(p1^ (%avl (%key p1) (%data p1) 0
p^ (%right p1))))
(values p1^ #f)))
((-1 0)
(let* ((p2 (%left p1))
(bal2 (%bal p2))
(p^ (%avl (%key p) (%data p)
(- (max bal2 0))
(%left p) (%left p2)))
(p1^ (%avl (%key p1) (%data p1)
(- (min bal2 0))
(%right p2) (%right p1)))
(p2^ (%avl (%key p2) (%data p2) 0
p^ p1^)))
(values p2^ #f)))
(else (internal-error))))
(else (internal-error)))))))
(else
(values (%avl key data (%bal p) (%left p) (%right p))
#f))))
(avl-check-usage
(procedure? pred<?)
"avl-insert expects a procedure as first argument")
(if (avl-empty? tree)
(%avl key data 0 #f #f)
(let-values (((p fix-balance?) (search tree #f)))
p)))
 
(define (internal-error)
(display "internal error\n" (current-error-port))
(emergency-exit 123))
 
(define (usage-error msg)
(display "Procedure usage error:\n" (current-error-port))
(display " " (current-error-port))
(display msg (current-error-port))
(newline (current-error-port))
(exit 1))
 
)) ;; end library (avl-trees)
 
 
(define-library (associative-arrays)
;;
;; Persistent associative ‘arrays’ for R7RS Scheme.
;;
;; The structure is not actually an array, but is made of AVL trees
;; and association lists. Given a good hash function, it should
;; average logarithmic performance.
;;
 
(export assoc-array-make-pair-generator
assoc-array-make-key-generator
assoc-array-make-data-generator)
(export assoc-array assoc-array? assoc-array-set assoc-array-ref)
 
(import (scheme base))
(import (scheme case-lambda))
(import (scheme write))
(import (suspendable-procedures))
(import (avl-trees))
 
(cond-expand
(chicken (import (only (srfi 1) alist-delete)))
;; Insert whatever you need here for your Scheme.
(else))
 
(begin
 
(define-record-type <assoc-array>
(%assoc-array hashfunc pred=? default table)
assoc-array?
(hashfunc %hashfunc)
(pred=? %pred=?)
(default %default)
(table %table))
 
(define (assoc-array-make-generator array kind)
(define tree-traverser (avl-make-generator (%table array)))
(define get-desired-part
(cond ((eq? kind 'key) (lambda (pair) (car pair)))
((eq? kind 'data) (lambda (pair) (cdr pair)))
(else (lambda (pair) pair))))
(make-generator-procedure
(lambda ()
(let traverse ()
(let ((tree-entry (tree-traverser)))
(when (success? tree-entry)
(let scan-lst ((lst (cdr tree-entry)))
(when (pair? lst)
(suspend (get-desired-part (car lst)))
(scan-lst (cdr lst))))
(traverse))))
&fail)))
 
(define (assoc-array-make-pair-generator array)
(assoc-array-make-generator array 'pair))
 
(define (assoc-array-make-key-generator array)
(assoc-array-make-generator array 'key))
 
(define (assoc-array-make-data-generator array)
(assoc-array-make-generator array 'data))
 
(define assoc-array
(case-lambda
((hashfunc)
(let ((pred=? equal?)
(default #f))
(assoc-array hashfunc pred=? default)))
((hashfunc pred=?)
(let ((default #f))
(assoc-array hashfunc pred=? default)))
((hashfunc pred=? default)
(%assoc-array hashfunc pred=? default (avl)))))
 
(define (assoc-array-set array key data)
(let ((hashfunc (%hashfunc array))
(pred=? (%pred=? array))
(default (%default array))
(table (%table array)))
(let ((hash-value (hashfunc key)))
(let*-values
(((alst found?) (avl-search-values < table hash-value)))
(cond
(found?
(let* ((alst (alist-delete key alst pred=?))
(alst `((,key . ,data) . ,alst))
(table (avl-insert < table hash-value alst)))
(%assoc-array hashfunc pred=? default table)))
(else
(let* ((alst `((,key . ,data)))
(table (avl-insert < table hash-value alst)))
(%assoc-array hashfunc pred=? default table))))))))
 
(define (assoc-array-ref array key)
(let* ((hashfunc (%hashfunc array))
(hash-value (hashfunc key)))
(let*-values
(((alst found?)
(avl-search-values < (%table array) hash-value)))
(if found?
(let ((pair (assoc key alst (%pred=? array))))
(if pair
(cdr pair)
(%default array)))
(%default array)))))
 
)) ;; end library (associative-arrays)
 
 
(cond-expand
(DEMONSTRATION
(begin
(import (scheme base))
(import (scheme write))
(import (suspendable-procedures))
(import (associative-arrays))
 
(define (hashfunc s)
;; Using Knuth’s random number generator to concoct a quick and
;; dirty and probably very bad hash function. It should be much
;; better to use something like SpookyHash, but this is a demo.
(define a 6364136223846793005)
(define c 1442695040888963407)
(define M (expt 2 64))
(let ((n (string-length s))
(h 123))
(do ((i 0 (+ i 1)))
((= i n))
(let* ((x (char->integer (string-ref s i)))
(x (+ (* a (+ h x)) c)))
(set! h (truncate-remainder x M))))
h))
 
(define a (assoc-array hashfunc))
 
;; Fill the associative array ‘a’ with (string . number)
;; associations.
(do ((i 1 (+ i 1)))
((= i 11))
(set! a (assoc-array-set a (number->string i) i)))
 
;; Go through the association pairs (in arbitrary order) with a
;; generator.
(let ((gen (assoc-array-make-pair-generator a)))
(do ((pair (gen) (gen)))
((failure? pair))
(write pair) (display " "))
(newline))
 
;; Go through the keys (in arbitrary order) with a generator.
(let ((gen (assoc-array-make-key-generator a)))
(do ((key (gen) (gen)))
((failure? key))
(write key) (display " "))
(newline))
 
;; Go through the values (in arbitrary order) with a generator.
(let ((gen (assoc-array-make-data-generator a)))
(do ((value (gen) (gen)))
((failure? value))
(write value) (display " "))
(newline))
 
))
(else))</syntaxhighlight>
{{out}}
<pre>$ csc -DDEMONSTRATION -R r7rs -X r7rs associative_array_with_generators.scm && ./associative_array_with_generators
("3" . 3) ("6" . 6) ("9" . 9) ("1" . 1) ("4" . 4) ("7" . 7) ("2" . 2) ("10" . 10) ("5" . 5) ("8" . 8)
"3" "6" "9" "1" "4" "7" "2" "10" "5" "8"
3 6 9 1 4 7 2 10 5 8</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: dictType is hash [string] integer;
Line 2,286 ⟶ 4,085:
writeln("value = " <& number);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,299 ⟶ 4,098:
value = 1
value = 2
</pre>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put {name:"Fluffy", type:"Rabbit", color:"White"} into animal
put "Carries a watch" into animal's habits
 
put "The animal: " & animal
put "The keys: " & keys of animal
put "The values: " & animal's values
// Keys and Values
put ,"All Properties:"
repeat with each [key,value] in animal
put !"Key: [[key]] Value: [[value]]"
end repeat
 
// Keys only
put ,"Keys:"
repeat with each [key] in animal
put key
end repeat
 
// Values only
put ,"Values:"
repeat with each [,value] in animal
put value
end repeat
 
// Using an iterator
put ,"Treating the property list as an iterator:"
put animal's nextValue -- calling any of the "next" functions begins iteration
put animal's nextKeyValue
put animal's nextKey
put animal's nextKeyValue
put animal's nextValue -- walking off the end returns a unique endValue
</syntaxhighlight>
{{out}}
<pre>
The animal: {color:"White", habits:"Carries a watch", name:"Fluffy", type:"Rabbit"}
The keys: ["color","habits","name","type"]
The values: ["White","Carries a watch","Fluffy","Rabbit"]
 
All Properties:
Key: color Value: White
Key: habits Value: Carries a watch
Key: name Value: Fluffy
Key: type Value: Rabbit
 
Keys:
color
habits
name
type
 
Values:
White
Carries a watch
Fluffy
Rabbit
 
Treating the property list as an iterator:
White
["habits","Carries a watch"]
name
["type","Rabbit"]
    ⓔ ⓝ ⓓ    
</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
Line 2,309 ⟶ 4,173:
# Iterate over key-value pairs
hash.each { |key, value|
say "#{key}: #{value}";
}
 
# Iterate only over keys
hash.keys.each { |key|
say key;
}
 
# Iterate only over values
hash.values.each { |value|
say value;
}</langsyntaxhighlight>
{{out}}
<pre>key1: value1
Line 2,332 ⟶ 4,196:
=={{header|Slate}}==
In Slate, all associative mappings inherit from <tt>Mapping</tt>, so they all have the same protocol. Even <tt>Sequence</tt>s obey it, in addition to their own protocol for collections with ordered integer-range keys.
<langsyntaxhighlight lang="slate">define: #pairs -> ({'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3} as: Dictionary).
pairs keysAndValuesDo: [| :key :value |
inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')'
Line 2,343 ⟶ 4,207:
pairs do: [| :value |
inform: 'value = ' ; value printString
].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">|pairs|
pairs := Dictionary
from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.
Line 2,365 ⟶ 4,229:
pairs do: [ :value |
('value = %1' % { value }) displayNl
].</langsyntaxhighlight>
 
We could also obtain a set of keys or a collection of values and iterate over them with "<tt>do:</tt>":
 
<langsyntaxhighlight lang="smalltalk">(pairs keys) do: [ :k | "..." ].
(pairs values) do: [ :v | "..." ].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 2,378 ⟶ 4,242:
{{works with|CSnobol}}
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Create sample table
t = table()
t<'cat'> = 'meow'
Line 2,393 ⟶ 4,257:
* # Iterate vals
vloop k = k + 1; output = a<k,2> :s(vloop)
end</langsyntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
// Create an associative array
a=asarray_create()
asarray(a,"one",1)
asarray(a,"two",2)
 
// Loop over entries
loc=asarray_first(a)
do {
printf("%s %f\n",asarray_key(a,loc),asarray_contents(a,loc))
loc=asarray_next(a,loc)
} while(loc!=NULL)
end</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">let myMap = [
"hello": 13,
"world": 31,
Line 2,403 ⟶ 4,282:
// iterating over key-value pairs:
for (key, value) in myMap {
println print("key = \(key), value = \(value)")
}
}</lang>
// Just the keys
for key in myMap.keys
{
print("key = \(key)")
}
// Just the values
for value in myMap.values
{
print("value = \(value)")
}</syntaxhighlight>
 
=={{header|Tcl}}==
===With Arrays===
<langsyntaxhighlight lang="tcl">array set myAry {
# list items here...
}
Line 2,423 ⟶ 4,312:
 
# There is nothing for directly iterating over just the values
# Use the keys+values version and ignore the keys</langsyntaxhighlight>
===With Dictionaries===
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">set myDict [dict create ...]; # Make the dictionary
 
# Iterate over keys and values
Line 2,441 ⟶ 4,330:
foreach value [dict values $myDict] {
puts "value = $value"
}</langsyntaxhighlight>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txrlisp">(defvarl h (hash))
 
(each ((k '(a b c))
Line 2,452 ⟶ 4,341:
 
(dohash (k v h)
(put-line `@k -> @v`))</langsyntaxhighlight>
 
{{out|Run}}
Line 2,462 ⟶ 4,351:
 
=={{header|UNIX Shell}}==
TwoAt least two shells have associative arrays, but they use different syntax to access their keys.
 
{{works with|ksh93}}
{{works with|bash|4.0 and above}}
<lang bash>typeset -A a=([key1]=value1 [key2]=value2)
<syntaxhighlight lang="bash">typeset -A a=([key1]=value1 [key2]=value2)
 
# just keys
Line 2,476 ⟶ 4,366:
for key in "${!a[@]}"; do
printf '%s => %s\n' "$key" "${a[$key]}"
done</langsyntaxhighlight>
 
{{works with|zsh}}
<langsyntaxhighlight lang="bash">typeset -A a
a=(key1 value1 key2 value2)
 
Line 2,489 ⟶ 4,379:
 
# keys and values
printf '%s => %s\n' ${(kv)a}</langsyntaxhighlight>
 
=={{header|Vala}}==
{{libheader|Gee}}
<langsyntaxhighlight lang="vala">
using Gee;
 
Line 2,523 ⟶ 4,413:
}
}
</syntaxhighlight>
</lang>
 
Compile with flag:
Line 2,542 ⟶ 4,432:
3.140000
</pre>
 
=={{header|VBA}}==
Dictionaries are similar in VBA and VBScript. Here is how to iterate.
 
<syntaxhighlight lang="vb">Option Explicit
Sub Test()
Dim h As Object, i As Long, u, v, s
Set h = CreateObject("Scripting.Dictionary")
h.Add "A", 1
h.Add "B", 2
h.Add "C", 3
 
'Iterate on keys
For Each s In h.Keys
Debug.Print s
Next
 
'Iterate on values
For Each s In h.Items
Debug.Print s
Next
 
'Iterate on both keys and values by creating two arrays
u = h.Keys
v = h.Items
For i = 0 To h.Count - 1
Debug.Print u(i), v(i)
Next
End Sub</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'instantiate the dictionary object
Set dict = CreateObject("Scripting.Dictionary")
Line 2,557 ⟶ 4,476:
WScript.StdOut.WriteLine key & " - " & dict.Item(key)
Next
</syntaxhighlight>
</lang>
 
{{Out}}
Line 2,567 ⟶ 4,486:
 
=={{header|Vim Script}}==
<langsyntaxhighlight lang="vim">let dict = {"apples": 11, "oranges": 25, "pears": 4}
 
echo "Iterating over key-value pairs"
Line 2,584 ⟶ 4,503:
for value in values(dict)
echo value
endfor</langsyntaxhighlight>
 
{{Out}}
Line 2,601 ⟶ 4,520:
4
11</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
my_map := {
"hello": 13,
"world": 31,
"!" : 71 }
// iterating over key-value pairs:
for key, value in my_map {
println("key = $key, value = $value")
}
// iterating over keys:
for key,_ in my_map {
println("key = $key")
}
// iterating over values:
for _, value in my_map {
println("value = $value")
}
}</syntaxhighlight>
 
{{out}}
<pre>key = hello, value = 13
key = world, value = 31
key = !, value = 71
key = hello
key = world
key = !
value = 13
value = 31
value = 71
</pre>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">h <- (table 'a 1 'b 2)
each (key val) table
prn key " " val</langsyntaxhighlight>
 
{{out}}
<pre>a 1
b 2</pre>
 
=={{header|Wren}}==
Note that Wren makes no guarantee about iteration order which is not necessarily the same order in which the entries were added.
<syntaxhighlight lang="wren">// create a new map with four entries
var capitals = {
"France": "Paris",
"Germany": "Berlin",
"Russia": "Moscow",
"Spain": "Madrid"
}
 
// iterate through the map and print out the key/value pairs
for (c in capitals) System.print([c.key, c.value])
System.print()
 
// iterate though the map and print out just the keys
for (k in capitals.keys) System.print(k)
System.print()
 
// iterate though the map and print out just the values
for (v in capitals.values) System.print(v)</syntaxhighlight>
 
{{out}}
<pre>
[France, Paris]
[Russia, Moscow]
[Germany, Berlin]
[Spain, Madrid]
 
France
Russia
Germany
Spain
 
Paris
Moscow
Berlin
Madrid
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
Line 2,631 ⟶ 4,624:
for I:= 0 to Entries-1 do
[ChOut(0, Dict(I,0)); ChOut(0, ^ ); Text(0, @Dict(I,1)); CrLf(0)];
]</langsyntaxhighlight>
 
{{out}}
Line 2,642 ⟶ 4,635:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var d=DDictionary("A","alpha","D","delta", "B","beta", "C", "gamma");
d.keys.pump(Console.print,fcn(k){String(k,",")})
d.values.apply("toUpper").println();
d.makeReadOnly(); // can only iterate over k,v pairs if read only
foreach k,v in (d){print(k,":",v,"; ")}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,656 ⟶ 4,649:
{{omit from|Applesoft BASIC}}
{{omit from|Brainf***}}
{{omit from|Commodore BASIC}}
{{omit from|Integer BASIC}}
{{omit from|TI-89 BASIC}} <!-- No builtin assoc arrays, would not be enlightening to show a defn -->
3,048

edits