Associative array/Iteration: Difference between revisions
→{{header|UNIX Shell}}: mention bash
(→{{header|UNIX Shell}}: mention bash) |
|||
(38 intermediate revisions by 28 users not shown) | |||
Line 1:
[[Category:Data Structures]]
{{task|Basic language learning}}Show how to iterate over the key-value pairs of an associative array, and print each pair out.
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
Line 9 ⟶ 10:
=={{header|11l}}==
<
L(key, value) d
Line 18 ⟶ 19:
L(value) d.values()
print(value)</
{{out}}
<pre>
Line 31 ⟶ 32:
=={{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
Line 42 ⟶ 43:
Iterating the keys uses "m:keys":
<syntaxhighlight lang="forth">
{"one": 1, "two": "bad"} m:keys
( . cr )
a:each
</syntaxhighlight>
{{out}}<pre>
one
Line 53 ⟶ 54:
=={{header|Ada}}==
<
with Ada.Containers.Indefinite_Ordered_Maps;
Line 71 ⟶ 72:
Index := Next (Index);
end loop;
end Test_Iteration;</
{{out}}
<pre>
Line 80 ⟶ 81:
=={{header|Aime}}==
<
text s;
Line 91 ⟶ 92:
o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s));
} while (rsk_greater(r, s, s));
}</
{{out}}
<pre>key A, value 33 (integer)
Line 101 ⟶ 102:
<br>
This sample defines a simple hash-based implementation with operators to iterate over the array.
<
# the modes allowed as associative array element values - change to suit #
Line 255 ⟶ 256:
e := NEXT a1
OD
END</
{{out}}
<pre>
Line 271 ⟶ 272:
=={{header|Arturo}}==
<
name: "john"
surname: "doe"
age:
]
loop
print ["key =
]
print "----"
loop
print ["key =
]
print "----"
loop
print ["value =
]</syntaxhighlight>
{{out}}
<pre>key =
key =
key =
----
key =
key =
key =
----
value =
value =
value =
=={{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]<
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t</
=={{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 {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
# iterate over keys, undefined order
for(key in a) {
print key, a[key]
}
}</syntaxhighlight>
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]
}
}</
=={{header|Babel}}==
Line 338 ⟶ 355:
In Babel, associative arrays are referred to as maps. To create a map from a list-of-lists:
<
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:
<
To see the results, use the valmap operator:
<syntaxhighlight lang
{{out}}
Line 353 ⟶ 370:
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:
<
{{out}}
Line 360 ⟶ 377:
To convert the entire map back to a list of key-value pairs:
<syntaxhighlight lang
To view the list:
<
{{out}}
Line 374 ⟶ 391:
To merge two maps together, use the mapmerge utility:
<
births foo mergemap !</
To view the results:
<
{{out}}
Line 391 ⟶ 408:
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|
==={{header|BaCon}}===
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING
associative("abc") = "first three"
Line 401 ⟶ 419:
FOR i = 0 TO amount - 1
PRINT keys$[i], ":", associative(keys$[i])
NEXT</
{{out}}
Line 410 ⟶ 428:
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}}===
<
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
Line 439 ⟶ 457:
key$ = MID$(dict$, J%+1, K%-J%-1)
IF K% >= LEN(dict$) THEN K% = 0
= K%</
=={{header|Bracmat}}==
<
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
Line 459 ⟶ 477:
& put$\n
)
);</
{{out}}
<pre>key: meat
Line 477 ⟶ 495:
=={{header|Brat}}==
<
#Iterate over key, value pairs
Line 492 ⟶ 510:
h.each_value { v |
p "Value: #{v}"
}</
=={{header|C}}==
''Solution is at [[Associative arrays/Creation/C]]''.
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
Line 531 ⟶ 549:
}
}
</syntaxhighlight>
=={{header|C++}}==
{{works with|C++11}}
<
#include <map>
#include <string>
Line 555 ⟶ 573:
return 0;
}</
Pre C++11:
<
myDict["hello"] = 1;
myDict["world"] = 2;
Line 570 ⟶ 588:
int& value = it->second;
std::cout << "key = " << key << ", value = " << value << std::endl;
}</
=={{header|Ceylon}}==
<
value myMap = map {
Line 593 ⟶ 611:
}
}</
=={{header|Chapel}}==
<
for k in A.domain do
Line 606 ⟶ 624:
for (k,v) in zip(A.domain, A) do
writeln("have element: ", k, " -> ", v);</
{{out}}
Line 620 ⟶ 638:
=={{header|Clojure}}==
<
(doseq [[k v] {:a 1, :b 2, :c 3}]
(println k "=" v))
Line 629 ⟶ 647:
(doseq [v (vals {:a 1, :b 2, :c 3})]
(println v))
</syntaxhighlight>
=={{header|CoffeeScript}}==
<
a: 'one'
b: 'two'
Line 641 ⟶ 659:
for key of hash
console.log key
</syntaxhighlight>
=={{header|Common Lisp}}==
Line 650 ⟶ 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.
<
(dolist (pair alist)
(destructuring-bind (key . value) pair
Line 657 ⟶ 675:
;; iterate and destructure with loop
(loop for (key . value) in alist
do (format t "~&Key: ~a, Value: ~a." key value))</
===With property lists (plists)===
Line 663 ⟶ 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.
<
do (format t "~&Key: ~a, Value: ~a." key value))</
===With hash tables===
Line 670 ⟶ 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.
<
(format t "~&Key: ~a, Value: ~a." key value))
hash-table)</
The <code>loop</code> construct also supports extracting key/value pairs from hash tables.
<
do (format t "~&Key: ~a, Value: ~a." key value))</
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.
<
(loop
(multiple-value-bind (nextp key value) (next-entry)
(if (not nextp)
(return)
(format t "~&Key: ~a, Value: ~a." key value)))))</
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
<
;; Project : Associative array/Iteration
Line 702 ⟶ 720:
(format t "~a" " : ")
(format t "~a" (aref x n 1)))
</syntaxhighlight>
Output:
<pre>
Line 709 ⟶ 727:
! : 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}}
<
void main() {
Line 752 ⟶ 793:
foreach (value; aa.values)
writeln("7) Got value ", value);
}</
=={{header|Dao}}==
<
dict = { 'def' => 1, 'abc' => 2 }
Line 763 ⟶ 804:
io.writeln( key, value )
}
</syntaxhighlight>
=={{header|Dart}}==
<
main(){
var fruits = {
Line 785 ⟶ 826:
fruits.values.forEach( ( value ) => print( value ) );
}
</syntaxhighlight>
{{out}}
<pre>
Line 811 ⟶ 852:
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 839 ⟶ 880:
lDictionary.Free;
end;
end.</
=={{header|Dyalect}}==
<syntaxhighlight lang
for x in t.
print("\(x)=\(t[x])")
}</
{{out}}
Line 861 ⟶ 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>).
<
"a" => 1,
"b" => 2,
Line 881 ⟶ 922:
for key in map.domain() { # iterate over the set whose values are the keys
println(`$key .`)
}</
=={{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}}==
<
(lib 'hash) ;; load hash.lib
(define H (make-hash))
Line 909 ⟶ 960:
value-> 666
value-> 33
</syntaxhighlight>
=={{header|Elena}}==
ELENA 5.0 :
<
import system'routines;
import extensions;
Line 930 ⟶ 981:
map.forEach:
(keyValue){ console.printLine(keyValue.Key," : ",keyValue.Value) }
}</
=== Strong typed dictionary ===
<
import system'routines;
import extensions;
Line 950 ⟶ 1,001:
map.forEach:
(tuple){ console.printLine(tuple.Item1," : ",tuple.Item2) }
}</
=={{header|Elixir}}==
<
Enum.each(d, fn kv -> IO.inspect kv end)
Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
Enum.each(Map.keys(d), fn key -> IO.inspect key end)
Enum.each(Map.values(d), fn value -> IO.inspect value end)</
{{out}}
Line 974 ⟶ 1,025:
3
1
</pre>
=={{header|EMal}}==
<syntaxhighlight lang="emal">
Map map = text%text["Italy" => "Rome", "France" => "Paris"]
map.insert("Germany", "Berlin")
map["Spain"] = "Madrid"
writeLine("== pairs ==")
for each Pair pair in map
writeLine(pair)
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}}==
<
-module(assoc).
-compile([export_all]).
Line 991 ⟶ 1,079:
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
end, dict:fetch_keys(D)).
</syntaxhighlight>
{{out}}
Line 1,001 ⟶ 1,089:
=={{header|F_Sharp|F#}}==
Iterating over both.
<
let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]
for k, v in myMap do
printfn "%s -> %d" k v
</syntaxhighlight>
Iterating over either keys or values only can be achieved through use of the _ wildcard token.
<
// Only prints the keys.
for k, _ in myMap do
Line 1,017 ⟶ 1,105:
for _, v in myMap do
printfn "%d" v
</syntaxhighlight>
=={{header|Factor}}==
<
<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 1,027 ⟶ 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.
<
class Main
{
Line 1,050 ⟶ 1,141:
}
}
</syntaxhighlight>
=={{header|Forth}}==
{{libheader|Forth Foundation Library}}
<
include ffl/hci.fs
Line 1,076 ⟶ 1,167:
;
iterate</
<
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
Line 1,216 ⟶ 1,307:
some-languages kill-association
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,275 ⟶ 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:<
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses Generics.Collections;
Line 1,307 ⟶ 1,438:
lDictionary.Free;
end;
end.</
<pre>
Pair: foo = 6
Line 1,320 ⟶ 1,451:
=={{header|Frink}}==
<
for [key, value] = d
println["$key\t$value"]
Line 1,327 ⟶ 1,458:
for key = keys[d]
println["$key"]
</syntaxhighlight>
{{out}}
Line 1,337 ⟶ 1,468:
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]'''
<
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
Line 1,355 ⟶ 1,584:
Next
End</
Output:
<pre>
Line 1,364 ⟶ 1,593:
=={{header|Go}}==
'''Language:'''
<
"hello": 13,
"world": 31,
Line 1,382 ⟶ 1,611:
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}</
'''Standard library templates:'''
Line 1,390 ⟶ 1,619:
* 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.
<
import (
Line 1,424 ⟶ 1,653:
{{end -}}
`)).Execute(os.Stdout, m)
}</
{{out}}
Note order by key.
Line 1,441 ⟶ 1,670:
=={{header|Groovy}}==
Solution:
<
println "Entries:"
Line 1,452 ⟶ 1,681:
println()
println "Values:"
map.values().each { println it }</
{{out}}
Line 1,477 ⟶ 1,706:
=={{header|Harbour}}==
<
LOCAL x
Line 1,487 ⟶ 1,716:
// or value only
? x
NEXT</
=={{header|Haskell}}==
with Data.Map:
<
myMap :: M.Map String Int
Line 1,503 ⟶ 1,732:
, show . M.elems -- Values
] <*>
pure myMap</
{{Out}}
<pre>[("!",71),("hello",13),("world",31)]
Line 1,510 ⟶ 1,739:
=={{header|Icon}} and {{header|Unicon}}==
<
t := table()
every t[a := !"ABCDE"] := map(a)
Line 1,524 ⟶ 1,753:
every writes(" ",!t)
write()
end</
{{out}}
Line 1,537 ⟶ 1,766:
=={{header|Io}}==
<
"hello", 13,
"world", 31,
Line 1,560 ⟶ 1,789:
myDict values foreach( value,
writeln("value = ", value)
)</
=={{header|J}}==
Line 1,568 ⟶ 1,797:
Using the J example from [[Creating an Associative Array]]...
Keys <syntaxhighlight lang
Values <syntaxhighlight lang
Both keys and values <
Note that this last is not likely to be useful in any practical context outside of learning the language.
=={{header|
<syntaxhighlight lang="jakt">
fn main() {
let dictionary = ["foo": 1, "bar": 2]
for entry in dictionary {
// To get values, use
// let value = entry.1
println("{}", entry)
}
// Just keys
for key in dictionary.keys() {
}
}
</syntaxhighlight>
{{out}}
<pre>
("bar", 2)
("foo", 1)
bar
foo
</pre>
=={{header|Java}}==
<p>
See also, [https://rosettacode.org/wiki/Associative_array/Creation#Java Java - Associative array/Creation].
</p>
<p>
You can access the <kbd>key</kbd> and <kbd>value</kbd> pairs by using the <code>Map.entrySet</code> method,
which will return a <code>Map.Entry</code>.<br />
It's worth noting that a <code>Map.Entry</code> also has the <code>setValue</code> method.
<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
<
map.put("hello", 1);
map.put("world", 2);
Line 1,615 ⟶ 1,874:
// iterating over values:
map.values().forEach(v -> System.out.printf("value = %s%n", v));</
{{out}}
Line 1,630 ⟶ 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.
<
myhash["hello"] = 3;
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name
Line 1,647 ⟶ 1,906:
keys.map(function (key) {
console.log("Key is: " + key + '. Value is: ' + myhash[key]);
});</
=={{header|Jq}}==
Line 1,662 ⟶ 1,921:
In jq > 1.4, keys_unsorted, for producing an array of the keys (in the order of creation), is also available.
<
# Iterating over the keys
Line 1,693 ⟶ 1,952:
# ["world",31]
# ["!",71]
</syntaxhighlight>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
# applying a function to key-value pairs:
Line 1,716 ⟶ 1,975:
@show value
end
</syntaxhighlight>
{{out}}
Line 1,733 ⟶ 1,992:
=={{header|K}}==
Creating a dictionary.
<
The keys are available via "!".
<
`hello `world `"!"
Line 1,742 ⟶ 2,001:
("hello"
"world"
,"!")</
Print the key value pairs.
<
hello: 1
world: 2
!: 3</
The values are available via "[]".
<
1 2 3
{x+1}'d[]
2 3 4</
=={{header|Kotlin}}==
<syntaxhighlight lang
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
with(map) {
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}
}</
{{Out}}
<pre>key = hello, value = 1
Line 1,779 ⟶ 2,038:
=={{header|Lang5}}==
<
: say(*) dup first " => " 2 compress "" join . second . ;
[['foo 5] ['bar 10] ['baz 20]] 'say apply drop</
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">
//iterate over associative array
//Lasso maps
Line 1,815 ⟶ 2,074:
//the {^ ^} indicates that output should be printed (AutoCollect) ,
// if output is not desired, just { } is used
</syntaxhighlight>
=={{header|LFE}}==
===Keys and Values===
<
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,828 ⟶ 2,087:
0
hash))
</syntaxhighlight>
===Just Keys===
<
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,838 ⟶ 2,097:
(: io format '"~s~n" (list key)))
(: dict fetch_keys hash)))
</syntaxhighlight>
=={{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">
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,866 ⟶ 2,125:
end
</syntaxhighlight>
Number of key-data pairs =5
Key 1: red Data: 255 50 50
Line 1,875 ⟶ 2,134:
=={{header|Lingo}}==
<
-- iterate over key-value pairs
Line 1,885 ⟶ 2,144:
repeat with val in hash
put val
end repeat</
=={{header|LiveCode}}==
<
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
Line 1,911 ⟶ 2,170:
-- alternatively, use same loop as for values 1 with tkey && fruit[tKey]
put tTmp</
Output
<
apples
pears
Line 1,924 ⟶ 2,183:
bananas:none
oranges:6
pears:5</
=={{header|Lua}}==
<
["foo"] = "bar",
["baz"] = 6,
Line 1,935 ⟶ 2,194:
for key,val in pairs(t) do
print(string.format("%s: %s", key, val))
end</
{{out}}
Line 1,946 ⟶ 2,205:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
Line 2,004 ⟶ 2,263:
}
Checkit
</syntaxhighlight>
=={{header|M4}}==
<
define(`for',
`ifelse($#,0,``$0'',
Line 2,041 ⟶ 2,300:
for(`x',1,asize(`a'),
`avalue(`a',x)
')</
{{out}}
Line 2,060 ⟶ 2,319:
=={{header|Maple}}==
Iterate through indices when indices are all simple expressions:
<syntaxhighlight lang="maple">
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
Line 2,070 ⟶ 2,329:
"D"
</syntaxhighlight>
Iterate through indices when indices may be expression sequences:
<syntaxhighlight lang="maple">
> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ):
> for i in indices( T ) do print( i, T[ op( i ) ] ) end:
Line 2,081 ⟶ 2,340:
["c", "d"], 3
</syntaxhighlight>
Return all index / entry pairs as equations:
<syntaxhighlight lang="maple">
> for i in indices( T, pairs ) do print( i) end:
"a" = 1
Line 2,091 ⟶ 2,350:
("c", "d") = 3
</syntaxhighlight>
<syntaxhighlight lang="maple">
> for i in entries( T ) do print( i) end:
[1]
Line 2,100 ⟶ 2,359:
[2]
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
hashes=#/@keys[#]&;
Line 2,110 ⟶ 2,369:
->{2,sometext}
hashes[a]
->{string,23}</
=={{header|MATLAB}} / {{header|Octave}}==
Line 2,116 ⟶ 2,375:
Associative arrays can be defined as structs in Matlab and Octave.
<
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; </
or
<
for k=1:length(keys),
key = keys{k};
value = hash.(key); % get value of key
hash.(key) = -value; % set value of key
end; </
=={{header|Maxima}}==
<
h[9]: 2$
Line 2,143 ⟶ 2,402:
for key in rest(arrayinfo(h), 2) do (
val: arrayapply(h, key),
print(key, val))$</
=={{header|MiniScript}}==
<
for keyVal in d
Line 2,158 ⟶ 2,417:
for val in d.values
print val
end for</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols
Line 2,174 ⟶ 2,433:
loop fn over surname
say fn.right(10) ':' surname[fn]
end fn</
=={{header|NewLISP}}==
<
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
Line 2,188 ⟶ 2,447:
;; loop over the assocation list:
(dolist (elem alist)
(println (format "%s -> %s" (first elem) (last elem))))</
=={{header|Nim}}==
<
import tables
var t: Table[int,string]
t[1] = "one"
t[2] = "two"
t[3] = "three"
t
echo "t has " & $t.len & " elements"
Line 2,211 ⟶ 2,470:
echo "at[" & $k & "]=" & t[k]
#
echo "pair iteration:"
for k,v in t.pairs:
echo "at[" & $k & "]=" & v
</syntaxhighlight>
{{out}}
<pre>
Line 2,235 ⟶ 2,494:
=={{header|Oberon-2}}==
{{works with|oo2c Version 2}}
<
MODULE AssociativeArray;
IMPORT
Line 2,277 ⟶ 2,536:
END AssociativeArray.
</syntaxhighlight>
=={{header|Objeck}}==
<
class Iteration {
function : Main(args : String[]) ~ Nil {
Line 2,306 ⟶ 2,565:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
{{works with|Objective-C|2.0+}}
<
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,323 ⟶ 2,582:
for (id value in [myDict objectEnumerator]) {
NSLog(@"value = %@", value);
}</
{{works with|Objective-C|<2.0}}
<
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,343 ⟶ 2,602:
while ((value = [enm nextObject])) {
NSLog(@"value = %@", value);
}</
{{works with|Cocoa|Mac OS X 10.6+}}
<
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,354 ⟶ 2,613:
[myDict enumerateKeysAndObjectsUsingBlock: ^(id key, id value, BOOL *stop) {
NSLog(@"key = %@, value = %@", key, value);
}];</
=={{header|OCaml}}==
Association array:
<
let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;
Line 2,372 ⟶ 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 ;;</
Hash table:
<
Hashtbl.add map 'A' 1;;
Hashtbl.add map 'B' 2;;
Line 2,384 ⟶ 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" ;;</
Functional binary search tree:
<
let map = CharMap.empty;;
let map = CharMap.add 'A' 1 map;;
Line 2,397 ⟶ 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" ;;</
=={{header|Ol}}==
<syntaxhighlight lang="ol">
;;; create sample associative array
(define aa (list->ff '(
Line 2,460 ⟶ 2,719:
; ==> #((! . 9) (hello . 1) (world . 4))
</syntaxhighlight>
=={{header|ooRexx}}==
<
d["hello"] = 1
d["world"] = 2
Line 2,483 ⟶ 2,742:
say "key =" s~index", value =" s~item
s~next
end</
{{out}}
<pre>key = !
Line 2,496 ⟶ 2,755:
=={{header|Oz}}==
<
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</
=={{header|PARI/GP}}==
Line 2,507 ⟶ 2,766:
The keys can be retried from a map with Vec:
<
You can iterate over the values as usual:
<
print(keys[i]," ",mapget(M,keys[i]))
)</
=={{header|Perl}}==
<
use strict;
Line 2,545 ⟶ 2,804:
foreach my $val ( values %pairs ) {
print "value = $val\n";
}</
=={{header|Phix}}==
The first three lines create a simple dictionary, with keys and values of several different types (string/integer/sequence):
<!--<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: #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>
Line 2,564 ⟶ 2,826:
{"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>
<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>
<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>
Line 2,577 ⟶ 2,847:
=={{header|Phixmonti}}==
<
def getd /# dict key -- dict data #/
swap 1 get rot find nip
dup if
else
drop "Unfound"
Line 2,597 ⟶ 2,858:
enddef
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
swap idata sget
2 tolist
enddef
def scandict /# dict n -- dict ( ) #/
var n
1 get len nip
for
pair
print nl
endfor
enddef
def pairs /# dict -- dict ( ) #/
0 scandict
enddef
Line 2,628 ⟶ 2,904:
/# ---------- MAIN ---------- #/
( ( ) ( ) )
( "one" 1 ) setd
Line 2,635 ⟶ 2,913:
pairs nl
keys nl
values
</syntaxhighlight>
=={{header|PHP}}==
<
$pairs = array( "hello" => 1,
"world" => 2,
Line 2,657 ⟶ 2,936:
echo "values = $value\n";
}
?></
=={{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===
<
(put 'A 'bar 10)
(put 'A 'baz 15)
Line 2,672 ⟶ 2,994:
: (mapcar car (getl 'A)) # Get all values
-> (15 10 5)</
===Using an index tree===
<
(idx 'A (def "bar" 10) T)
(idx 'A (def "baz" 15) T)
Line 2,685 ⟶ 3,007:
: (mapcar val (idx 'A)) # Get all values
-> (10 15 5)</
=={{header|Pike}}==
Line 2,691 ⟶ 3,013:
the order is deterministic however.
<syntaxhighlight lang="pike">
mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]);
foreach(m; string key; string value)
Line 2,713 ⟶ 3,035:
Result: bac
</syntaxhighlight>
=={{header|PostScript}}==
<
% over keys and values
<</a 1 /b 2 /c 3>> {= =} forall
Line 2,723 ⟶ 3,045:
% just values
<</a 1 /b 2 /c 3>> {pop =} forall
</syntaxhighlight>
=={{header|Potion}}==
We can traverse tables by key or by key and val. We cannot traverse tables only by val.
<
mydictionary each (key, val): (key, ":", val, "\n") join print.
mydictionary each (key): (key, "\n") join print.</
=={{header|PowerShell}}==
Using the following hash table:
<
Iterating over the key/value pairs is slightly cumbersome as it requires an explicit call to <code>GetEnumerator</code>:
<
A <code>foreach</code> statement can also be used:
<
Write-Host Key: $e.Name, Value: $e.Value
}</
Iterating over the keys:
<
foreach ($k in $h.Keys) {
Write-Host Key: $k
}</
Iterating over the values:
<
foreach ($v in $h.Values) {
Write-Host Value: $v
}</
=={{header|Prolog}}==
Line 2,759 ⟶ 3,081:
from having more than one value):
<
assert( mymap(key1,value1) ).
assert( mymap(key2,value1) ).
</syntaxhighlight>
To perform the specific task at hand:
<
?- forall( mymap(Key,Value), writeln( [Key,Value]) ).
[key1,value1]
[key2,value1]
</syntaxhighlight>
In Prolog, however, iteration is "built-in". For example:
<
?- mymap(key1, Y).
Y = value1.
Line 2,780 ⟶ 3,102:
X = key1 ;
X = key2.
</syntaxhighlight>
To construct the list of keys:
<
?- findall( X, mymap(X,value1), Xs).
Xs = [key1, key2].
</syntaxhighlight>
To construct the list of distinct values:
<
?- findall( Y, mymap(key1,Y), Ys).
Ys = [value1].
</syntaxhighlight>
=={{header|PureBasic}}==
Hashes are a built-in type called Map in Purebasic.
<
dict("de") = "German"
dict("en") = "English"
Line 2,804 ⟶ 3,126:
ForEach dict()
Debug MapKey(dict()) + ":" + dict()
Next</
=={{header|Python}}==
<
"world": 31,
"!" : 71 }
Line 2,824 ⟶ 3,146:
# iterating over values:
for value in myDict.values():
print ("value = %s" % value)</
=={{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 2,832 ⟶ 3,277:
=== environment example ===
<
> env[["x"]] <- 123
> env[["x"]]</
<pre>[1] 123</pre>
<
> env[[index]] <- "rainfed hay"
> for (name in ls(env)) {
+ cat(sprintf('index=%s, value=%s\n', name, env[[name]]))
+ }</
<pre>index=1, value=rainfed hay
index=x, value=123</pre>
Line 2,846 ⟶ 3,291:
=== vector example ===
<
> print(x["!"])</
<pre>!
3</pre>
<
<pre>[1] 3</pre>
=== list example ===
<
> print(a$a)</
<pre>[1] 1</pre>
<syntaxhighlight lang
<pre>[1] "xyz"</pre>
Line 2,864 ⟶ 3,309:
Using the dictionary interface, different data structures can be treated as an associative array in Racket.
<
#lang racket
Line 2,875 ⟶ 3,320:
(for/list ([(k v) (in-dict dict3)]) ; => '("0 -> a" "1 -> b" "2 -> c")
(format "~a -> ~a" k v))
</syntaxhighlight>
=={{header|Raku}}==
Line 2,881 ⟶ 3,326:
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku"
for %pairs.kv -> $k, $v {
Line 2,896 ⟶ 3,341:
say "key = $_" for %pairs.keys;
say "value = $_" for %pairs.values;</
=={{header|REXX}}==
<
/*╔════════════════════════════════════════════════════════════════════════════════════╗
║ The (below) two REXX statements aren't really necessary, but it shows how to ║
Line 2,956 ⟶ 3,401:
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.*/</
{{out|output|text= when using the internal default input:}}
<pre>
Line 2,989 ⟶ 3,434:
=={{header|Ring}}==
<
# Project : Associative array/Iteration
Line 2,996 ⟶ 3,441:
see lst[n][1] + " : " + lst[n][2] + nl
next
</syntaxhighlight>
Output:
<pre>
Line 3,007 ⟶ 3,452:
Associative arrays are called ''lists'' in RLaB.
<syntaxhighlight lang="rlab">
x = <<>>; // create an empty list
x.hello = 1;
Line 3,032 ⟶ 3,477:
</syntaxhighlight>
=={{header|Ruby}}==
<
"world" => 31,
"!" => 71 }
Line 3,048 ⟶ 3,493:
# iterating over values:
my_dict.each_value {|value| puts "value =#{value}"}</
another way:
<
puts "key = #{key}, value = #{value}"
end
Line 3,061 ⟶ 3,506:
for value in my_dict.values
puts "value = #{value}"
end</
{{out}}
Line 3,077 ⟶ 3,522:
=={{header|Rust}}==
<
fn main() {
let mut olympic_medals = HashMap::new();
Line 3,089 ⟶ 3,534:
}
}</
{{out}}
Note that <code>HashMap</code> does not preserve order (if this is important, <code>std::collections::BTreeMap</code> is what you want.)
Line 3,100 ⟶ 3,545:
=={{header|Scala}}==
<
println(f"Key->Value: ${m.mkString(", ")}%s")
Line 3,106 ⟶ 3,551:
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s")</
Key->Value: Amsterdam -> Netherlands, New York -> USA, Heemstede -> Netherlands
Pairs: (Amsterdam,Netherlands), (New York,USA), (Heemstede,Netherlands)
Line 3,118 ⟶ 3,563:
{{works with|Gauche Scheme}}
<syntaxhighlight lang="scheme">
;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
Line 3,129 ⟶ 3,574:
;; Create by "partial application" a function that accepts 2 arguments,
;; the key and the value:
(pa$ format #t "Key = ~a, Value = ~a\n"))</
Output:
Line 3,138 ⟶ 3,583:
</pre>
<syntaxhighlight lang="scheme">
;; Iterate over the table and create a list of the keys and the
;; altered values:
Line 3,150 ⟶ 3,595:
(lambda (k-v) (cons (car k-v) (+ (cdr k-v) 5000)))
table)
</syntaxhighlight>
To get a list of the keys or of the values of the table,
Line 3,159 ⟶ 3,604:
(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}}==
<
const type: dictType is hash [string] integer;
Line 3,189 ⟶ 4,058:
writeln("value = " <& number);
end for;
end func;</
{{out}}
Line 3,202 ⟶ 4,071:
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}}==
<
key1 => 'value1',
key2 => 'value2',
Line 3,212 ⟶ 4,146:
# 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
}</
{{out}}
<pre>key1: value1
Line 3,235 ⟶ 4,169:
=={{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.
<
pairs keysAndValuesDo: [| :key :value |
inform: '(k, v) = (' ; key printString ; ', ' ; value printString ; ')'
Line 3,246 ⟶ 4,180:
pairs do: [| :value |
inform: 'value = ' ; value printString
].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
pairs := Dictionary
from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.
Line 3,268 ⟶ 4,202:
pairs do: [ :value |
('value = %1' % { value }) displayNl
].</
We could also obtain a set of keys or a collection of values and iterate over them with "<tt>do:</tt>":
<
(pairs values) do: [ :v | "..." ].</
=={{header|SNOBOL4}}==
Line 3,281 ⟶ 4,215:
{{works with|CSnobol}}
<
t = table()
t<'cat'> = 'meow'
Line 3,296 ⟶ 4,230:
* # Iterate vals
vloop k = k + 1; output = a<k,2> :s(vloop)
end</
=={{header|Stata}}==
<
// Create an associative array
a=asarray_create()
Line 3,311 ⟶ 4,245:
loc=asarray_next(a,loc)
} while(loc!=NULL)
end</
=={{header|Swift}}==
<
"hello": 13,
"world": 31,
Line 3,321 ⟶ 4,255:
// iterating over key-value pairs:
for (key, value) in myMap {
}
// 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===
<
# list items here...
}
Line 3,341 ⟶ 4,285:
# There is nothing for directly iterating over just the values
# Use the keys+values version and ignore the keys</
===With Dictionaries===
{{works with|Tcl|8.5}}
<
# Iterate over keys and values
Line 3,359 ⟶ 4,303:
foreach value [dict values $myDict] {
puts "value = $value"
}</
=={{header|TXR}}==
<
(each ((k '(a b c))
Line 3,370 ⟶ 4,314:
(dohash (k v h)
(put-line `@k -> @v`))</
{{out|Run}}
Line 3,380 ⟶ 4,324:
=={{header|UNIX Shell}}==
{{works with|ksh93}}
{{works with|bash|4.0 and above}}
<syntaxhighlight lang="bash">typeset -A a=([key1]=value1 [key2]=value2)
# just keys
Line 3,394 ⟶ 4,339:
for key in "${!a[@]}"; do
printf '%s => %s\n' "$key" "${a[$key]}"
done</
{{works with|zsh}}
<
a=(key1 value1 key2 value2)
Line 3,407 ⟶ 4,352:
# keys and values
printf '%s => %s\n' ${(kv)a}</
=={{header|Vala}}==
{{libheader|Gee}}
<
using Gee;
Line 3,441 ⟶ 4,386:
}
}
</syntaxhighlight>
Compile with flag:
Line 3,464 ⟶ 4,409:
Dictionaries are similar in VBA and VBScript. Here is how to iterate.
<
Sub Test()
Dim h As Object, i As Long, u, v, s
Line 3,488 ⟶ 4,433:
Debug.Print u(i), v(i)
Next
End Sub</
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'instantiate the dictionary object
Set dict = CreateObject("Scripting.Dictionary")
Line 3,504 ⟶ 4,449:
WScript.StdOut.WriteLine key & " - " & dict.Item(key)
Next
</syntaxhighlight>
{{Out}}
Line 3,514 ⟶ 4,459:
=={{header|Vim Script}}==
<
echo "Iterating over key-value pairs"
Line 3,531 ⟶ 4,476:
for value in values(dict)
echo value
endfor</
{{Out}}
Line 3,548 ⟶ 4,493:
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}}==
<
each (key val) table
prn key " " val</
{{out}}
Line 3,560 ⟶ 4,540:
=={{header|Wren}}==
Note that Wren makes no guarantee about iteration order which is not necessarily the same order in which the entries were added.
<
var capitals = {
"France": "Paris",
Line 3,577 ⟶ 4,557:
// iterate though the map and print out just the values
for (v in capitals.values) System.print(v)</
{{out}}
Line 3,598 ⟶ 4,578:
=={{header|XPL0}}==
<
char Dict(10,10);
int Entries;
Line 3,617 ⟶ 4,597:
for I:= 0 to Entries-1 do
[ChOut(0, Dict(I,0)); ChOut(0, ^ ); Text(0, @Dict(I,1)); CrLf(0)];
]</
{{out}}
Line 3,628 ⟶ 4,608:
=={{header|zkl}}==
<
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,"; ")}</
{{out}}
<pre>
|