Associative array/Iteration: Difference between revisions

m
Automated syntax highlighting fixup (second round - minor fixes)
m (syntax highlighting fixup automation)
m (Automated syntax highlighting fixup (second round - minor fixes))
Line 1:
{{task|Basic language learning}}[[Category:Iteration]][[Category:Data Structures]]
[[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}}==
<syntaxhighlight lang="11l">V d = [‘key1’ = ‘value1’, ‘key2’ = ‘value2’]
 
L(key, value) d
Line 31 ⟶ 32:
=={{header|8th}}==
Iterating key,value pairs uses "m:each":
<syntaxhighlight lang=Forth"forth">
{"one": 1, "two": "bad"}
( swap . space . cr )
Line 42 ⟶ 43:
 
Iterating the keys uses "m:keys":
<syntaxhighlight lang=Forth"forth">
{"one": 1, "two": "bad"} m:keys
( . cr )
Line 53 ⟶ 54:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;
 
Line 80 ⟶ 81:
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">record r;
text s;
 
Line 101 ⟶ 102:
<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 #
Line 271 ⟶ 272:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; create a dictionary
d: #[
name: "john"
Line 316 ⟶ 317:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
From the [http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/objects/Enumerator.htm documentation]<syntaxhighlight lang=AutoHotkey"autohotkey">; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
Line 325 ⟶ 326:
=={{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
Line 339 ⟶ 340:
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
Line 354 ⟶ 355:
In Babel, associative arrays are referred to as maps. To create a map from a list-of-lists:
 
<syntaxhighlight lang="babel">births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! <</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="babel">births cp dup {1 +} overmap !</syntaxhighlight>
 
To see the results, use the valmap operator:
 
<syntaxhighlight lang="babel">valmap ! lsnum !</syntaxhighlight>
 
{{out}}
Line 369 ⟶ 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:
 
<syntaxhighlight lang="babel">births ('Roosevelt' 'Kennedy') lumapls ! lsnum !</syntaxhighlight>
 
{{out}}
Line 376 ⟶ 377:
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}}
Line 390 ⟶ 391:
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}}
Line 408 ⟶ 409:
 
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING
 
associative("abc") = "first three"
Line 430 ⟶ 431:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
Line 458 ⟶ 459:
 
=={{header|Bracmat}}==
<syntaxhighlight lang="bracmat">( new$hash:?myhash
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
Line 493 ⟶ 494:
 
=={{header|Brat}}==
<syntaxhighlight lang="brat">h = [ hello: 1 world: 2 :! : 3]
 
#Iterate over key, value pairs
Line 514 ⟶ 515:
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 551 ⟶ 552:
=={{header|C++}}==
{{works with|C++11}}
<syntaxhighlight lang="cpp">#include <iostream>
#include <map>
#include <string>
Line 575 ⟶ 576:
 
Pre C++11:
<syntaxhighlight lang="cpp">std::map<std::string, int> myDict;
myDict["hello"] = 1;
myDict["world"] = 2;
Line 589 ⟶ 590:
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">shared void run() {
 
value myMap = map {
Line 613 ⟶ 614:
=={{header|Chapel}}==
 
<syntaxhighlight lang="chapel">var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ];
 
for k in A.domain do
Line 636 ⟶ 637:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
(doseq [[k v] {:a 1, :b 2, :c 3}]
(println k "=" v))
Line 648 ⟶ 649:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">hash =
a: 'one'
b: 'two'
Line 666 ⟶ 667:
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.
 
<syntaxhighlight lang="lisp">;; iterate using dolist, destructure manually
(dolist (pair alist)
(destructuring-bind (key . value) pair
Line 679 ⟶ 680:
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.
 
<syntaxhighlight lang="lisp">(loop for (key value) on plist :by 'cddr
do (format t "~&Key: ~a, Value: ~a." key value))</syntaxhighlight>
 
Line 686 ⟶ 687:
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.
 
<syntaxhighlight lang="lisp">(maphash (lambda (key value)
(format t "~&Key: ~a, Value: ~a." key value))
hash-table)</syntaxhighlight>
Line 692 ⟶ 693:
The <code>loop</code> construct also supports extracting key/value pairs from hash tables.
 
<syntaxhighlight 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))</syntaxhighlight>
 
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.
 
<syntaxhighlight lang="lisp">(with-hash-table-iterator (next-entry hash-table)
(loop
(multiple-value-bind (nextp key value) (next-entry)
Line 706 ⟶ 707:
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<syntaxhighlight lang="lisp">
;; Project : Associative array/Iteration
 
Line 727 ⟶ 728:
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">dict = {'A' => 1, 'B' => 2}
 
dict.each { |pair|
Line 752 ⟶ 753:
{{works with|D|2}}
 
<syntaxhighlight lang="d">import std.stdio: writeln;
 
void main() {
Line 794 ⟶ 795:
 
=={{header|Dao}}==
<syntaxhighlight lang="ruby">
dict = { 'def' => 1, 'abc' => 2 }
 
Line 805 ⟶ 806:
 
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
main(){
var fruits = {
Line 850 ⟶ 851:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program AssociativeArrayIteration;
 
{$APPTYPE CONSOLE}
Line 882 ⟶ 883:
=={{header|Dyalect}}==
 
<syntaxhighlight lang="dyalect">var t = (x: 1, y: 2, z: 3)
 
for x in t.Keys() {
Line 900 ⟶ 901:
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>).
 
<syntaxhighlight lang="e">def map := [
"a" => 1,
"b" => 2,
Line 923 ⟶ 924:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'hash) ;; load hash.lib
(define H (make-hash))
Line 952 ⟶ 953:
=={{header|Elena}}==
ELENA 5.0 :
<syntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 972 ⟶ 973:
 
=== Strong typed dictionary ===
<syntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 992 ⟶ 993:
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">IO.inspect d = Map.new([foo: 1, bar: 2, baz: 3])
Enum.each(d, fn kv -> IO.inspect kv end)
Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
Line 1,016 ⟶ 1,017:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(assoc).
-compile([export_all]).
Line 1,040 ⟶ 1,041:
=={{header|F_Sharp|F#}}==
Iterating over both.
<syntaxhighlight lang="fsharp">
let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]
 
Line 1,048 ⟶ 1,049:
 
Iterating over either keys or values only can be achieved through use of the _ wildcard token.
<syntaxhighlight lang="fsharp">
// Only prints the keys.
for k, _ in myMap do
Line 1,059 ⟶ 1,060:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">H{ { "hi" "there" } { "a" "b" } } [ ": " glue print ] assoc-each</syntaxhighlight>
<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,069 ⟶ 1,070:
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.
 
<syntaxhighlight lang="fantom">
class Main
{
Line 1,097 ⟶ 1,098:
{{libheader|Forth Foundation Library}}
 
<syntaxhighlight lang="forth">include ffl/hct.fs
include ffl/hci.fs
 
Line 1,120 ⟶ 1,121:
iterate</syntaxhighlight>
 
<syntaxhighlight lang="forth">
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
Line 1,325 ⟶ 1,326:
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
Line 1,360 ⟶ 1,361:
 
=={{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;
Line 1,402 ⟶ 1,403:
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">d = new dict[[[1, "one"], [2, "two"]]]
for [key, value] = d
println["$key\t$value"]
Line 1,422 ⟶ 1,423:
=={{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
Line 1,446 ⟶ 1,447:
=={{header|Go}}==
'''Language:'''
<syntaxhighlight lang="go">myMap := map[string]int {
"hello": 13,
"world": 31,
Line 1,472 ⟶ 1,473:
* 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 (
Line 1,523 ⟶ 1,524:
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
 
println "Entries:"
Line 1,559 ⟶ 1,560:
 
=={{header|Harbour}}==
<syntaxhighlight lang="visualfoxpro">LOCAL arr := { 6 => 16, "eight" => 8, "eleven" => 11 }
LOCAL x
 
Line 1,573 ⟶ 1,574:
=={{header|Haskell}}==
with Data.Map:
<syntaxhighlight lang="haskell">import qualified Data.Map as M
 
myMap :: M.Map String Int
Line 1,592 ⟶ 1,593:
 
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
t := table()
every t[a := !"ABCDE"] := map(a)
Line 1,619 ⟶ 1,620:
 
=={{header|Io}}==
<syntaxhighlight lang=Io"io">myDict := Map with(
"hello", 13,
"world", 31,
Line 1,650 ⟶ 1,651:
Using the J example from [[Creating an Associative Array]]...
 
Keys <syntaxhighlight lang=J"j">nl__example 0</syntaxhighlight>
 
Values <syntaxhighlight lang=J"j">get__example each nl__example 0</syntaxhighlight>
 
Both keys and values <syntaxhighlight lang=J"j">(,&< get__example) each nl__example 0</syntaxhighlight>
 
Note that this last is not likely to be useful in any practical context outside of learning the language.
 
=={{header|Java}}==
<syntaxhighlight lang="java">Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 1);
map.put("world", 2);
Line 1,683 ⟶ 1,684:
Java 8 version
 
<syntaxhighlight lang="java">Map<String, Integer> map = new HashMap<>();
map.put("hello", 1);
map.put("world", 2);
Line 1,712 ⟶ 1,713:
=={{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.
<syntaxhighlight 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,744 ⟶ 1,745:
 
In jq > 1.4, keys_unsorted, for producing an array of the keys (in the order of creation), is also available.
<syntaxhighlight lang="jq">def mydict: {"hello":13, "world": 31, "!": 71};
 
# Iterating over the keys
Line 1,779 ⟶ 1,780:
=={{header|Julia}}==
{{works with|Julia|0.6}}
<syntaxhighlight lang="julia">dict = Dict("hello" => 13, "world" => 31, "!" => 71)
 
# applying a function to key-value pairs:
Line 1,815 ⟶ 1,816:
=={{header|K}}==
Creating a dictionary.
<syntaxhighlight lang=K"k"> d: .((`"hello";1); (`"world";2);(`"!";3))</syntaxhighlight>
 
The keys are available via "!".
<syntaxhighlight lang=K"k"> !d
`hello `world `"!"
 
Line 1,827 ⟶ 1,828:
 
Print the key value pairs.
<syntaxhighlight lang=K"k"> `0:{,/$x,": ",d[x]}'!d
hello: 1
world: 2
Line 1,833 ⟶ 1,834:
 
The values are available via "[]".
<syntaxhighlight lang=K"k"> d[]
1 2 3
 
Line 1,840 ⟶ 1,841:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">fun main(a: Array<String>) {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
 
Line 1,861 ⟶ 1,862:
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: first 0 extract nip ; : second 1 extract nip ; : nip swap drop ;
: say(*) dup first " => " 2 compress "" join . second . ;
 
Line 1,867 ⟶ 1,868:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">
//iterate over associative array
//Lasso maps
Line 1,902 ⟶ 1,903:
 
===Keys and Values===
<syntaxhighlight lang="lisp">
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,913 ⟶ 1,914:
 
===Just Keys===
<syntaxhighlight lang="lisp">
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
Line 1,924 ⟶ 1,925:
=={{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,957 ⟶ 1,958:
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">hash = [#key1:"value1", #key2:"value2", #key3:"value3"]
 
-- iterate over key-value pairs
Line 1,970 ⟶ 1,971:
 
=={{header|LiveCode}}==
<syntaxhighlight lang=LiveCode"livecode">put 3 into fruit["apples"]
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
Line 1,995 ⟶ 1,996:
put tTmp</syntaxhighlight>
Output
<syntaxhighlight lang=LiveCode"livecode">Keys:
apples
pears
Line 2,009 ⟶ 2,010:
 
=={{header|Lua}}==
<syntaxhighlight lang="lua">local t = {
["foo"] = "bar",
["baz"] = 6,
Line 2,028 ⟶ 2,029:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
Line 2,089 ⟶ 2,090:
 
=={{header|M4}}==
<syntaxhighlight lang=M4"m4">divert(-1)
define(`for',
`ifelse($#,0,``$0'',
Line 2,142 ⟶ 2,143:
=={{header|Maple}}==
Iterate through indices when indices are all simple expressions:
<syntaxhighlight lang=Maple"maple">
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
Line 2,155 ⟶ 2,156:
 
Iterate through indices when indices may be expression sequences:
<syntaxhighlight lang=Maple"maple">
> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ):
> for i in indices( T ) do print( i, T[ op( i ) ] ) end:
Line 2,166 ⟶ 2,167:
 
Return all index / entry pairs as equations:
<syntaxhighlight lang=Maple"maple">
> for i in indices( T, pairs ) do print( i) end:
"a" = 1
Line 2,175 ⟶ 2,176:
</syntaxhighlight>
 
<syntaxhighlight lang=Maple"maple">
> for i in entries( T ) do print( i) end:
[1]
Line 2,185 ⟶ 2,186:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">keys=DownValues[#,Sort->False][[All,1,1,1]]&;
hashes=#/@keys[#]&;
 
Line 2,198 ⟶ 2,199:
Associative arrays can be defined as structs in Matlab and Octave.
 
<syntaxhighlight lang=Matlab"matlab"> keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
Line 2,207 ⟶ 2,208:
or
 
<syntaxhighlight lang=Matlab"matlab"> keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
Line 2,215 ⟶ 2,216:
 
=={{header|Maxima}}==
<syntaxhighlight lang=Maxima"maxima">h[1]: 6$
h[9]: 2$
 
Line 2,228 ⟶ 2,229:
 
=={{header|MiniScript}}==
<syntaxhighlight lang=MiniScript"miniscript">d = { 3: "test", "foo": 3 }
 
for keyVal in d
Line 2,243 ⟶ 2,244:
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
options replace format comments java crossref symbols
 
Line 2,259 ⟶ 2,260:
 
=={{header|NewLISP}}==
<syntaxhighlight lang=NewLISP"newlisp">;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
 
Line 2,273 ⟶ 2,274:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
import tables
 
Line 2,317 ⟶ 2,318:
=={{header|Oberon-2}}==
{{works with|oo2c Version 2}}
<syntaxhighlight lang="oberon2">
MODULE AssociativeArray;
IMPORT
Line 2,362 ⟶ 2,363:
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
class Iteration {
function : Main(args : String[]) ~ Nil {
Line 2,392 ⟶ 2,393:
=={{header|Objective-C}}==
{{works with|Objective-C|2.0+}}
<syntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,408 ⟶ 2,409:
 
{{works with|Objective-C|<2.0}}
<syntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,428 ⟶ 2,429:
 
{{works with|Cocoa|Mac OS X 10.6+}}
<syntaxhighlight lang="objc">NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:13], @"hello",
[NSNumber numberWithInt:31], @"world",
Line 2,440 ⟶ 2,441:
=={{header|OCaml}}==
Association array:
<syntaxhighlight lang="ocaml">#!/usr/bin/env ocaml
 
let map = [| ('A', 1); ('B', 2); ('C', 3) |] ;;
Line 2,457 ⟶ 2,458:
 
Hash table:
<syntaxhighlight lang="ocaml">let map = Hashtbl.create 42;;
Hashtbl.add map 'A' 1;;
Hashtbl.add map 'B' 2;;
Line 2,469 ⟶ 2,470:
 
Functional binary search tree:
<syntaxhighlight lang="ocaml">module CharMap = Map.Make (Char);;
let map = CharMap.empty;;
let map = CharMap.add 'A' 1 map;;
Line 2,482 ⟶ 2,483:
 
=={{header|Ol}}==
<syntaxhighlight lang="ol">
;;; create sample associative array
(define aa (list->ff '(
Line 2,545 ⟶ 2,546:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">d = .directory~new
d["hello"] = 1
d["world"] = 2
Line 2,578 ⟶ 2,579:
 
=={{header|Oz}}==
<syntaxhighlight lang="oz">declare
MyMap = unit('hello':13 'world':31 '!':71)
in
Line 2,589 ⟶ 2,590:
 
The keys can be retried from a map with Vec:
<syntaxhighlight lang="parigp">keys = Vec(M);</syntaxhighlight>
You can iterate over the values as usual:
<syntaxhighlight lang="parigp">for(i=1,#keys,
print(keys[i]," ",mapget(M,keys[i]))
)</syntaxhighlight>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">#! /usr/bin/perl
use strict;
 
Line 2,631 ⟶ 2,632:
=={{header|Phix}}==
The first three lines create a simple dictionary, with keys and values of several different types (string/integer/sequence):
<!--<syntaxhighlight lang=Phix"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>
Line 2,650 ⟶ 2,651:
</pre>
You could also use some of the map.e routines:
<!--<syntaxhighlight lang=Phix"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>
Line 2,670 ⟶ 2,671:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def getd /# dict key -- dict data #/
Line 2,740 ⟶ 2,741:
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
$pairs = array( "hello" => 1,
"world" => 2,
Line 2,762 ⟶ 2,763:
 
=={{header|Picat}}==
<syntaxhighlight lang=Picat"picat">go =>
Map = new_map([1=one,2=two,3=three,4=four]),
foreach(K=V in Map)
Line 2,806 ⟶ 2,807:
=={{header|PicoLisp}}==
===Using properties===
<syntaxhighlight lang=PicoLisp"picolisp">(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
Line 2,819 ⟶ 2,820:
-> (15 10 5)</syntaxhighlight>
===Using an index tree===
<syntaxhighlight lang=PicoLisp"picolisp">(idx 'A (def "foo" 5) T)
(idx 'A (def "bar" 10) T)
(idx 'A (def "baz" 15) T)
Line 2,836 ⟶ 2,837:
the order is deterministic however.
 
<syntaxhighlight lang=Pike"pike">
mapping(string:string) m = ([ "A":"a", "B":"b", "C":"c" ]);
foreach(m; string key; string value)
Line 2,861 ⟶ 2,862:
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
% over keys and values
<</a 1 /b 2 /c 3>> {= =} forall
Line 2,872 ⟶ 2,873:
=={{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.
Line 2,879 ⟶ 2,880:
=={{header|PowerShell}}==
Using the following hash table:
<syntaxhighlight lang="powershell">$h = @{ 'a' = 1; 'b' = 2; 'c' = 3 }</syntaxhighlight>
Iterating over the key/value pairs is slightly cumbersome as it requires an explicit call to <code>GetEnumerator</code>:
<syntaxhighlight lang="powershell">$h.GetEnumerator() | ForEach-Object { Write-Host Key: $_.Name, Value: $_.Value }</syntaxhighlight>
A <code>foreach</code> statement can also be used:
<syntaxhighlight lang="powershell">foreach ($e in $h.GetEnumerator()) {
Write-Host Key: $e.Name, Value: $e.Value
}</syntaxhighlight>
Iterating over the keys:
<syntaxhighlight lang="powershell">$h.Keys | ForEach-Object { Write-Host Key: $_ }
 
foreach ($k in $h.Keys) {
Line 2,893 ⟶ 2,894:
}</syntaxhighlight>
Iterating over the values:
<syntaxhighlight lang="powershell">$h.Values | ForEach-Object { Write-Host Value: $_ }
 
foreach ($v in $h.Values) {
Line 2,904 ⟶ 2,905:
from having more than one value):
 
<syntaxhighlight lang="prolog">
assert( mymap(key1,value1) ).
assert( mymap(key2,value1) ).
Line 2,910 ⟶ 2,911:
 
To perform the specific task at hand:
<syntaxhighlight lang="prolog">
?- forall( mymap(Key,Value), writeln( [Key,Value]) ).
 
Line 2,918 ⟶ 2,919:
 
In Prolog, however, iteration is "built-in". For example:
<syntaxhighlight lang="prolog">
?- mymap(key1, Y).
Y = value1.
Line 2,928 ⟶ 2,929:
 
To construct the list of keys:
<syntaxhighlight lang="prolog">
?- findall( X, mymap(X,value1), Xs).
Xs = [key1, key2].
Line 2,934 ⟶ 2,935:
 
To construct the list of distinct values:
<syntaxhighlight lang="prolog">
?- findall( Y, mymap(key1,Y), Ys).
Ys = [value1].
Line 2,942 ⟶ 2,943:
Hashes are a built-in type called Map in Purebasic.
 
<syntaxhighlight lang="purebasic">NewMap dict.s()
dict("de") = "German"
dict("en") = "English"
Line 2,952 ⟶ 2,953:
 
=={{header|Python}}==
<syntaxhighlight lang="python">myDict = { "hello": 13,
"world": 31,
"!" : 71 }
Line 2,972 ⟶ 2,973:
 
=={{header|QB64}}==
<syntaxhighlight lang=QB64"qb64">
'dictionary is not native data type of QB64
' here a dictionary engine using a string to store data
Line 3,100 ⟶ 3,101:
=== environment example ===
 
<syntaxhighlight lang="r">> env <- new.env()
> env[["x"]] <- 123
> env[["x"]]</syntaxhighlight>
<pre>[1] 123</pre>
<syntaxhighlight lang="r">> index <- "1"
> env[[index]] <- "rainfed hay"
> for (name in ls(env)) {
Line 3,114 ⟶ 3,115:
=== vector example ===
 
<syntaxhighlight lang="r">> x <- c(hello=1, world=2, "!"=3)
> print(x["!"])</syntaxhighlight>
<pre>!
3</pre>
<syntaxhighlight lang="r">> print(unname(x["!"]))</syntaxhighlight>
<pre>[1] 3</pre>
 
=== list example ===
 
<syntaxhighlight lang=R"r">> a <- list(a=1, b=2, c=3.14, d="xyz")
> print(a$a)</syntaxhighlight>
<pre>[1] 1</pre>
<syntaxhighlight lang=R"r">> print(a$d)</syntaxhighlight>
<pre>[1] "xyz"</pre>
 
Line 3,132 ⟶ 3,133:
Using the dictionary interface, different data structures can be treated as an associative array in Racket.
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 3,149 ⟶ 3,150:
{{works with|Rakudo|2015.12}}
 
<syntaxhighlight lang=perl6"raku" line>my %pairs = hello => 13, world => 31, '!' => 71;
for %pairs.kv -> $k, $v {
Line 3,167 ⟶ 3,168:
 
=={{header|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 ║
Line 3,257 ⟶ 3,258:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Associative array/Iteration
 
Line 3,275 ⟶ 3,276:
Associative arrays are called ''lists'' in RLaB.
 
<syntaxhighlight lang=RLaB"rlab">
x = <<>>; // create an empty list
x.hello = 1;
Line 3,303 ⟶ 3,304:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">my_dict = { "hello" => 13,
"world" => 31,
"!" => 71 }
Line 3,319 ⟶ 3,320:
 
another way:
<syntaxhighlight lang="ruby">for key, value in my_dict
puts "key = #{key}, value = #{value}"
end
Line 3,345 ⟶ 3,346:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
Line 3,368 ⟶ 3,369:
 
=={{header|Scala}}==
<syntaxhighlight lang=Scala"scala">val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
 
println(f"Key->Value: ${m.mkString(", ")}%s")
Line 3,386 ⟶ 3,387:
{{works with|Gauche Scheme}}
 
<syntaxhighlight lang=Scheme"scheme">
;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
Line 3,406 ⟶ 3,407:
</pre>
 
<syntaxhighlight lang=Scheme"scheme">
;; Iterate over the table and create a list of the keys and the
;; altered values:
Line 3,439 ⟶ 3,440:
(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)))
Line 3,853 ⟶ 3,854:
 
=={{header|Seed7}}==
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: dictType is hash [string] integer;
Line 3,897 ⟶ 3,898:
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put {name:"Fluffy", type:"Rabbit", color:"White"} into animal
put "Carries a watch" into animal's habits
 
Line 3,962 ⟶ 3,963:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
Line 3,992 ⟶ 3,993:
=={{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.
<syntaxhighlight 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 4,008 ⟶ 4,009:
{{works with|GNU Smalltalk}}
 
<syntaxhighlight lang="smalltalk">|pairs|
pairs := Dictionary
from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.
Line 4,029 ⟶ 4,030:
We could also obtain a set of keys or a collection of values and iterate over them with "<tt>do:</tt>":
 
<syntaxhighlight lang="smalltalk">(pairs keys) do: [ :k | "..." ].
(pairs values) do: [ :v | "..." ].</syntaxhighlight>
 
Line 4,038 ⟶ 4,039:
{{works with|CSnobol}}
 
<syntaxhighlight lang=SNOBOL4"snobol4">* # Create sample table
t = table()
t<'cat'> = 'meow'
Line 4,056 ⟶ 4,057:
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
// Create an associative array
a=asarray_create()
Line 4,071 ⟶ 4,072:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">let myMap = [
"hello": 13,
"world": 31,
Line 4,083 ⟶ 4,084:
=={{header|Tcl}}==
===With Arrays===
<syntaxhighlight lang="tcl">array set myAry {
# list items here...
}
Line 4,101 ⟶ 4,102:
===With Dictionaries===
{{works with|Tcl|8.5}}
<syntaxhighlight lang="tcl">set myDict [dict create ...]; # Make the dictionary
 
# Iterate over keys and values
Line 4,120 ⟶ 4,121:
=={{header|TXR}}==
 
<syntaxhighlight lang="txrlisp">(defvarl h (hash))
 
(each ((k '(a b c))
Line 4,140 ⟶ 4,141:
 
{{works with|ksh93}}
<syntaxhighlight lang="bash">typeset -A a=([key1]=value1 [key2]=value2)
 
# just keys
Line 4,154 ⟶ 4,155:
 
{{works with|zsh}}
<syntaxhighlight lang="bash">typeset -A a
a=(key1 value1 key2 value2)
 
Line 4,168 ⟶ 4,169:
=={{header|Vala}}==
{{libheader|Gee}}
<syntaxhighlight lang="vala">
using Gee;
 
Line 4,221 ⟶ 4,222:
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
Line 4,248 ⟶ 4,249:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
'instantiate the dictionary object
Set dict = CreateObject("Scripting.Dictionary")
Line 4,271 ⟶ 4,272:
 
=={{header|Vim Script}}==
<syntaxhighlight lang="vim">let dict = {"apples": 11, "oranges": 25, "pears": 4}
 
echo "Iterating over key-value pairs"
Line 4,307 ⟶ 4,308:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">fn main() {
my_map := {
"hello": 13,
Line 4,342 ⟶ 4,343:
 
=={{header|Wart}}==
<syntaxhighlight lang="wart">h <- (table 'a 1 'b 2)
each (key val) table
prn key " " val</syntaxhighlight>
Line 4,352 ⟶ 4,353:
=={{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="ecmascript">// create a new map with four entries
var capitals = {
"France": "Paris",
Line 4,390 ⟶ 4,391:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
Line 4,420 ⟶ 4,421:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">var d=Dictionary("A","alpha","D","delta", "B","beta", "C", "gamma");
d.keys.pump(Console.print,fcn(k){String(k,",")})
d.values.apply("toUpper").println();
10,333

edits