Associative array/Creation: 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:Data Structures]]
{{task|Basic language learning}}
 
;Task:
The goal is to create an [[associative array]] (also known as a dictionary, map, or hash).
Line 14:
 
=={{header|11l}}==
<syntaxhighlight lang="11l">V dict = [‘key1’ = 1, ‘key2’ = 2]
V value2 = dict[‘key2’]</syntaxhighlight>
 
=={{header|8th}}==
8th has 'maps' as built-in data types, and can use JSON to describe them:
<syntaxhighlight lang=Forth"forth">
{ "one" : 1, "two" : "bad" }
</syntaxhighlight>
Alternatively, they can be created in code:
<syntaxhighlight lang=Forth"forth">
m:new "one" 1 m:! "two" "bad" m:!
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang=AArch64"aarch64 Assemblyassembly">
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */
/* program hashmap64.s */
Line 429:
=={{header|ActionScript}}==
Because ActionScript does not have associative arrays in the normal sense, Object objects are used instead and keys are simply properties on those objects.
<syntaxhighlight lang="actionscript">var map:Object = {key1: "value1", key2: "value2"};
trace(map['key1']); // outputs "value1"
 
Line 442:
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
<syntaxhighlight lang="ada">with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
Line 478:
=={{header|Aikido}}==
Aikido provides a native <em>map</em> for associative arrays. You can create them using a map literal and you can insert and remove items on the fly.
<syntaxhighlight lang="aikido">
var names = {} // empty map
names["foo"] = "bar"
Line 502:
=={{header|Aime}}==
Aime records are heterogenous associative arrays. No creation procedure is required, declaration is fine.
<syntaxhighlight lang="aime">record r;</syntaxhighlight>
<syntaxhighlight lang="aime">r_put(r, "A", 33); # an integer value
r_put(r, "C", 2.5); # a real value
r_put(r, "B", "associative"); # a string value</syntaxhighlight>
Line 514:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<syntaxhighlight lang="algol68">main:(
 
MODE COLOR = BITS;
Line 600:
 
Creating a new empty map of String to String:
<syntaxhighlight lang="apex">// Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap).
Map<String, String> strMap = new Map<String, String>();
strMap.put('a', 'aval');
Line 611:
 
Creating a new map of String to String with values initialized:
<syntaxhighlight lang="apex">Map<String, String> strMap = new Map<String, String>{
'a' => 'aval',
'b' => 'bval'
Line 621:
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">⍝ Create a namespace ("hash")
X←⎕NS ⍬
Line 645:
 
{{works with|GNU APL}}
<syntaxhighlight lang="apl">
⍝ Assign some names
X.this←'that'
Line 681:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang=ARM"arm Assemblyassembly">
/* ARM assembly Raspberry PI or android 32 bits */
/* program hashmap.s */
Line 1,057:
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; create a dictionary
d: #[
name: "john"
Line 1,078:
=== Persistent association lists ===
The following implementation includes set, get, and delete, and also "generators", which are like iterators except they are closures rather than regular objects.
<syntaxhighlight lang=ATS"ats">(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
Line 1,324:
Because the hash table is an AVL tree, performance will tend to be logarithmic. This assumes a good hash function, of course. With a bad hash function, performance may be linear.
 
<syntaxhighlight lang=ATS"ats">(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
Line 1,917:
=== True arrays ===
[[AutoHotkey_L]] has [http://ahkscript.org/docs/Objects.htm Objects] which function as associative arrays.
<syntaxhighlight lang=AutoHotkey"autohotkey">associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23}
MsgBox % associative_array.key1
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</syntaxhighlight>
Line 1,923:
[[AutoHotkey_Basic]] does not have typical arrays.
However, variable names can be concatenated, simulating associative arrays.
<syntaxhighlight lang=AutoHotkey"autohotkey">arrayX1 = first
arrayX2 = second
arrayX3 = foo
Line 1,932:
=={{header|AutoIt}}==
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.
<syntaxhighlight lang=AutoIt"autoit">; Associative arrays in AutoIt.
; All the required functions are below the examples.
 
Line 2,063:
=={{header|AWK}}==
Arrays in AWK are indeed associative arrays.
<syntaxhighlight lang="awk">BEGIN {
a["red"] = 0xff0000
a["green"] = 0x00ff00
Line 2,082:
=={{header|Babel}}==
 
<syntaxhighlight lang="babel">
(("foo" 13)
("bar" 42)
Line 2,088:
 
=={{header|BaCon}}==
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING
 
associative("abc") = "first three"
Line 2,103:
 
=={{header|BASIC256}}==
<syntaxhighlight lang=BASIC256"basic256">global values$, keys$
dim values$[1]
dim keys$[1]
Line 2,222:
This is cheating, I'm sure of it.
 
<syntaxhighlight lang="dos">::assocarrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
Line 2,259:
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
Line 2,283:
=={{header|Bracmat}}==
The hash is the only built-in Bracmat class. It is best used for e.g. a large dictionary, when manipulation of a very long list of key/value pairs with pattern matching would become too CPU-intensive. The same key can be stored with different values, as the example shows. If that is not desirable, the key (and its value) should be removed first.
<syntaxhighlight lang="bracmat"> new$hash:?myhash
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
Line 2,298:
 
=={{header|Brat}}==
<syntaxhighlight lang="brat">h = [:] #Empty hash
 
h[:a] = 1 #Assign value
Line 2,312:
=={{header|C sharp|C#}}==
'''Platform:''' [[.NET]] 1.x
<syntaxhighlight lang="csharp">System.Collections.HashTable map = new System.Collections.HashTable();
map["key1"] = "foo";</syntaxhighlight>
 
'''Platform:''' [[.NET]] 2.0
<syntaxhighlight lang="csharp">Dictionary<string, string> map = new Dictionary<string,string>();
map[ "key1" ] = "foo";</syntaxhighlight>
 
{{works with|C sharp|C#|3.0+}}
<syntaxhighlight lang="csharp">var map = new Dictionary<string, string> {{"key1", "foo"}};</syntaxhighlight>
 
=={{header|C++}}==
The C++ standard defines std::map as a means of creating an association between a key of one arbitrary type and a value of another arbitrary type. This requires the inclusion of the standard header '''map'''.
 
<syntaxhighlight lang="cpp">#include <map></syntaxhighlight>
 
===Creation===
To create a simple map whose key is of type A and whose value is of type B, one would define the variable like so:
<syntaxhighlight lang="cpp">std::map<A, B> exampleMap</syntaxhighlight>
 
If one wanted to us a key type of '''int''' and a value of '''double''', you would define it like so:
 
<syntaxhighlight lang="cpp">std::map<int, double> exampleMap</syntaxhighlight>
 
===Insertion===
Line 2,339:
====Operator[]====
The first method is using the [] operator.
<syntaxhighlight lang="cpp">exampleMap[7] = 3.14</syntaxhighlight>
 
Of course, you can use a variable (or any [[rvalue]] of the correct type) for the key or value parameters:
<syntaxhighlight lang="cpp">int myKey = 7;
double myValue = 3.14;
exampleMap[myKey] = myValue;</syntaxhighlight>
====insert()====
The second approach is a little more complicated. We have to use the '''pair<>''' template:
<syntaxhighlight lang="cpp">exampleMap.insert(std::pair<int, double>(7,3.14));</syntaxhighlight>
or by using '''make_pair''' to avoid repeating key/value types:
<syntaxhighlight lang="cpp">exampleMap.insert(std::make_pair(7,3.14));</syntaxhighlight>
 
===Lookup===
Line 2,355:
====operator[]====
We use it as an rvalue, supplying the correct key:
<syntaxhighlight lang="cpp">myValue = exampleMap[myKey]</syntaxhighlight>
If the value doesn't already exist, a default-constructed object of the value's type will be inserted using the key you specified, and that default value will be returned.
 
====find()====
Alternatively, you can look up a value by using find(), storing its return value in an [[iterator]], and comparing the iterator against the map's end() [[sentinal value]]:
<syntaxhighlight lang="cpp">double myValue = 0.0;
std::map<int, double>::iterator myIterator = exampleMap.find(myKey);
if(exampleMap.end() != myIterator)
Line 2,374:
===Example===
This simple program creates a map, assigns a value to that map, retrieves a value from that map, and prints the value to STDOUT.
<syntaxhighlight lang="cpp">#include <map>
#include <iostreams>
 
Line 2,402:
 
=={{header|Ceylon}}==
<syntaxhighlight lang="ceylon">import ceylon.collection {
 
ArrayList,
Line 2,444:
The creation of the domain is independent from the creation of the array, and in fact the same domain can be used for multiple arrays, creating associative arrays with identical sets of keys. When the domain is changed, all arrays that use it will be reallocated.
 
<syntaxhighlight lang="text">// arr is an array of string to int. any type can be used in both places.
var keys: domain(string);
var arr: [keys] int;
Line 2,483:
 
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">{:key "value"
:key2 "value2"
:key3 "value3"}</syntaxhighlight>
 
=={{header|ColdFusion}}==
<syntaxhighlight lang="cfm"><cfset myHash = structNew()>
<cfset myHash.key1 = "foo">
<cfset myHash["key2"] = "bar">
Line 2,496:
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">;; default :test is #'eql, which is suitable for numbers only,
;; or for implementation identity for other types!
;; Use #'equalp if you want case-insensitive keying on strings.
Line 2,513:
BlackBox Componente Builder<br/>
Using a handmade collections module with the following interface<br/>
<syntaxhighlight lang="oberon2">
DEFINITION Collections;
 
Line 2,583:
</syntaxhighlight>
The program:
<syntaxhighlight lang="oberon2">
MODULE BbtAssociativeArrays;
IMPORT StdLog, Collections, Boxes;
Line 2,614:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">hash1 = {"foo" => "bar"}
 
# hash literals that don't perfectly match the intended hash type must be given an explicit type specification
Line 2,621:
 
=={{header|D}}==
<syntaxhighlight lang="d">void main() {
auto hash = ["foo":42, "bar":100];
assert("foo" in hash);
Line 2,627:
 
=={{header|Dao}}==
<syntaxhighlight lang="dao">m = { => } # empty ordered map, future inserted keys will be ordered
h = { -> } # empty hash map, future inserted keys will not be ordered
 
Line 2,634:
 
=={{header|Dart}}==
<syntaxhighlight lang="javascript">
main() {
var rosettaCode = { // Type is inferred to be Map<String, String>
Line 2,687:
 
=={{header|Delphi}}==
<syntaxhighlight lang=Delphi"delphi">program AssociativeArrayCreation;
 
{$APPTYPE CONSOLE}
Line 2,711:
 
To create a dictionary associative array:
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_dict(tanzanianBanknoteObverseDipiction)_keys(500,1000,2000,5000,10000)_values(Karume,Nyerere,lion,black rhinoceros,elephant);
Line 2,718:
 
To create a hash associative array:
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_hash(tanzanianBanknoteReverseDipiction)_values(
Line 2,734:
Dyalect has a <code>Tuple</code> data type which allows to add labels to values:
 
<syntaxhighlight lang="dyalect">var t = (x: 1, y: 2, z: 3)
print(t.Keys().ToArray())</syntaxhighlight>
 
Line 2,742:
 
=={{header|E}}==
<syntaxhighlight lang="e">[].asMap() # immutable, empty
["one" => 1, "two" => 2] # immutable, 2 mappings
[].asMap().diverge() # mutable, empty
Line 2,749:
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="scheme">
(lib 'hash) ;; needs hash.lib
(define H (make-hash)) ;; new hash table
Line 2,772:
=={{header|Elena}}==
ELENA 5.0:
<syntaxhighlight lang="elena">import system'collections;
public program()
Line 2,786:
 
=== Strong typed dictionary ===
<syntaxhighlight lang="elena">import system'collections;
 
public program()
Line 2,801:
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule RC do
def test_create do
IO.puts "< create Map.new >"
Line 2,831:
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang=Lisp"lisp">(setq my-table (make-hash-table))
(puthash 'key 'value my-table)</syntaxhighlight>
 
<code>make-hash-table</code> compares keys with <code>eql</code> by default. This suits symbols and numbers (including floating point). For string keys an <code>equal</code> test can be used,
 
<syntaxhighlight lang=Lisp"lisp">(setq my-table (make-hash-table :test 'equal))
(puthash "key" 123 my-table)</syntaxhighlight>
 
Line 2,843:
=={{header|Erlang}}==
Erlang offers several associative array type data structures, this example uses the dictionary data structure.
<syntaxhighlight lang="erlang">
-module(assoc).
-compile([export_all]).
Line 2,870:
=={{header|F Sharp|F#}}==
.NET 3.5 Generic Dictionary (mutable)
<syntaxhighlight lang="fsharp">
let dic = System.Collections.Generic.Dictionary<string,string>() ;;
dic.Add("key","val") ;
Line 2,876:
</syntaxhighlight>
Functional dictionary (immutable)
<syntaxhighlight lang="fsharp">
let d = [("key","val");("other key","other val")] |> Map.ofList
let newd = d.Add("new key","new val")
Line 2,889:
Associative mappings follow the associative protocol. See [http://docs.factorcode.org/content/article-assocs-protocol.html the docs].
Here's an example using a hashtable that can be run in the listener :
<syntaxhighlight lang="factor">H{ { "one" 1 } { "two" 2 } }
{ [ "one" swap at . ]
[ 2 swap value-at . ]
Line 2,900:
Associative arrays are called 'maps' in Fantom:
 
<syntaxhighlight lang="fantom">
class Main
{
Line 2,925:
The Forth dictionary is normally only used for function and symbol definitions, but you can also define separate ''wordlists'' for holding functions or data. There is no special syntax in the language for this, but you can define your own. All of Forth's defining words are available for adding things to the wordlist, but CREATE is most generic.
 
<syntaxhighlight lang="forth">: get ( key len table -- data ) \ 0 if not present
search-wordlist if
>body @
Line 2,953:
 
Hashtable for mapping strings to integer
<syntaxhighlight lang="forth">include ffl/hct.fs
 
\ Create a hash table 'table' in the dictionary with a starting size of 10
Line 2,975:
 
Similar functionality is available in 4tH. A binary search is applied to search values, hence hashtables can be quite compact.
<syntaxhighlight lang="text">include lib/hash.4th
include lib/hashkey.4th
Line 3,002:
=={{header|FreeBASIC}}==
Uses unions to store the keys and associated values, and FreeBASIC's ability to resize arrays makes adding new entries easy.
<syntaxhighlight lang="freebasic">#define max(a, b) Iif(a>b,a,b)
 
enum datatype
Line 3,079:
=={{header|Free Pascal}}==
FPC 3.2.0.+. Similar to Delphi.
<syntaxhighlight lang="pascal">program AssociativeArrayCreation;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
Line 3,097:
end.</syntaxhighlight>
FPC 2.4+. Using FGL instead of rtl-generics:
<syntaxhighlight lang="pascal">program AssociativeArrayCreation;
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}
{$MODE DELPHI}
Line 3,116:
 
=={{header|Futhark}}==
<syntaxhighlight lang="futhark">let associative_array = {key1=1,key2=2}</syntaxhighlight>
 
=={{header|Gambas}}==
Line 3,123:
=={{header|Go}}==
Allowable key types are those with == and != operators. This includes is boolean, numeric, string, pointer, channel, and interface types. It also includes structs and arrays containing only these types. Disallowed as map keys are all slice, function, and map types.
<syntaxhighlight lang="go">// declare a nil map variable, for maps from string to int
var x map[string]int
 
Line 3,149:
=={{header|Gosu}}==
As an OOP language with generics Gosu can use any variety of Map classes. In addition Gosu provides associative array syntax for all objects.
<syntaxhighlight lang="javascript">// empty map
var emptyMap = new HashMap<String, Integer>()
 
Line 3,187:
=={{header|Groovy}}==
Create an empty map and add values
<syntaxhighlight lang="groovy">map = [:]
map[7] = 7
map['foo'] = 'foovalue'
Line 3,199:
 
Create a pre-populated map and verify values
<syntaxhighlight lang="groovy">map = [7:7, foo:'foovalue', bar:'barvalue', moo:'moovalue']
 
assert 7 == map[7]
Line 3,208:
=={{header|Harbour}}==
Create an empty array and add values:
<syntaxhighlight lang="visualfoxpro">arr := { => }
arr[ 10 ] := "Val_10"
arr[ "foo" ] := "foovalue"</syntaxhighlight>
Create and initialize array:
<syntaxhighlight lang="visualfoxpro">arr := hb_Hash( 10, "Val_10", "foo", "foovalue" )
// or
arr := { 10 => "Val_10", "foo" => "foovalue" }</syntaxhighlight>
Line 3,219:
Binary trees:
{{works with|GHC}}
<syntaxhighlight lang="haskell">import Data.Map
 
dict = fromList [("key1","val1"), ("key2","val2")]
Line 3,227:
 
It is also possible to use association lists (lists of pairs). It is inefficient (O(n) lookup), but simple.
<syntaxhighlight lang="haskell">dict = [("key1","val1"), ("key2","val2")]
 
ans = lookup "key2" dict -- evaluates to Just "val2"
Line 3,237:
 
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">let d dict 2 # Initial estimated size
let d["test"] "test" # Strings can be used as index
let d[123] 123 # Integers can also be used as index
Line 3,247:
Icon and Unicon associative arrays are called tables. Any value may be used as a key including complex structures. Tables can have default values and they have no inherent size limitation growing from empty to whatever size is needed.
 
<syntaxhighlight lang="icon">procedure main()
local t
t := table()
Line 3,258:
 
===Static relation===
<syntaxhighlight lang="inform7">Hash Bar is a room.
 
Connection relates various texts to one number. The verb to be connected to implies the connection relation.
Line 3,278:
 
===Dynamic relation===
<syntaxhighlight lang="inform7">Hash Bar is a room.
 
When play begins:
Line 3,295:
 
=={{header|Ioke}}==
<syntaxhighlight lang="ioke">{a: "a", b: "b"}</syntaxhighlight>
 
=={{header|J}}==
Line 3,303:
However, it's also possible to use the symbol table itself to hold the names. The symbol table has limitations (can only accept syntactically valid names), but we can turn arbitrary strings into valid symbols using base 62 encode and prefixing with a letter (hypothetically speaking, base 64 encode would let us build longer names than base 62, because of computational complexity issues - but the J symbol table also comes with a name length limit - 255 characters - and does not support 64 different characters in names):
 
<syntaxhighlight lang=J"j">coclass 'assocArray'
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i.
get=: ".@encode
Line 3,311:
Example use:
 
<syntaxhighlight lang="j"> example=: conew 'assocArray'
'foo' set__example 1 2 3
1 2 3
Line 3,331:
 
Defining the Map:
<syntaxhighlight lang="java5">Map<String, Integer> map = new HashMap<String, Integer>();
map.put("foo", 5);
map.put("bar", 10);
Line 3,339:
 
Initializing a Map as a class member:
<syntaxhighlight lang="java5">public static Map<String, Integer> map = new HashMap<String, Integer>(){{
put("foo", 5);
put("bar", 10);
Line 3,346:
}};</syntaxhighlight>
Retrieving a value:
<syntaxhighlight lang="java5">map.get("foo"); // => 6
map.get("invalid"); // => null</syntaxhighlight>
Note that it is possible to put <code>null</code> as a value, so <code>null</code> being returned by <code>get</code> is not sufficient for determining that the key is not in the <code>Map</code>. There is a <code>containsKey</code> method for that.
 
Iterate over keys:
<syntaxhighlight lang="java5">for (String key: map.keySet())
System.out.println(key);</syntaxhighlight>
Iterate over values:
<syntaxhighlight lang="java5">for (int value: map.values())
System.out.println(value);</syntaxhighlight>
Iterate over key, value pairs:
<syntaxhighlight lang="java5">for (Map.Entry<String, Integer> entry: map.entrySet())
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>
 
Line 3,364:
 
Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name. Using quotes on property names avoids potential collisions with reserved JavaScript key words.
<syntaxhighlight lang="javascript">var assoc = {};
 
assoc['foo'] = 'bar';
Line 3,388:
 
ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings.
<syntaxhighlight lang="javascript">var map = new Map(),
fn = function () {},
obj = {};
Line 3,414:
===Associative Arrays with String-Valued Keys===
In jq, JSON objects can be used as associative arrays, it being understood that only strings can be used as keys. To avoid confusion, for the remainder of this section, we refer to JSON objects as such. Their type in jq is "object".
<syntaxhighlight lang="jq"># An empty object:
{}
 
Line 3,440:
In this subsection, we define addKey(key;value), getKey(key), and removeKey(key)
to operate on a hash table for which the keys may be any JSON entities. This is done by defining a collisionless hash function.
<syntaxhighlight lang="jq">def collisionless:
if type == "object" then with_entries(.value = (.value|collisionless))|tostring
elif type == "array" then map(collisionless)|tostring
Line 3,456:
def removeKey(key): delpaths( [ [key|collisionless] ] );</syntaxhighlight>
'''Example''':
<syntaxhighlight lang="jq">{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</syntaxhighlight>
produces:
<syntaxhighlight lang="sh">"two"</syntaxhighlight>
 
=={{header|Jsish}}==
From Javascript. jsish warns of duplicate ''var'', in this case the ''assoc'' variable is reused.
<syntaxhighlight lang="javascript">var assoc = {};
assoc['foo'] = 'bar';
Line 3,503:
{{works with|Julia|0.6}}
We build dictionaries associating to some characters their code points, by listing the key/value pairs, through a dictionary comprehension, by creating an empty dictionary and filling it, by using the specific syntax associated to typed dictionaries.
<syntaxhighlight lang="julia">dict = Dict('a' => 97, 'b' => 98) # list keys/values
# Dict{Char,Int64} with 2 entries:
# 'b' => 98
Line 3,533:
=={{header|K}}==
Keys in a dictionary must be symbols (`symbol).
<syntaxhighlight lang=K"k"> / creating an dictionary
d1:.((`foo;1); (`bar;2); (`baz;3))
 
Line 3,541:
Another approach.
<syntaxhighlight lang=K"k"> d2: .() / create empty dictionary
d2[`"zero"]:0
d2[`"one"]:1
Line 3,552:
 
Extracting the keys and values.
<syntaxhighlight lang=K"k"> !d2 / the keys
`zero `one `two
 
Line 3,560:
=={{header|Kotlin}}==
{{trans|Java}}
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
// map definition:
val map = mapOf("foo" to 5,
Line 3,589:
=={{header|Lambdatalk}}==
Associative arrays are not currently built in the JS.js kernel of lambdatalk but are added via the lib_hash library page.
<syntaxhighlight lang="scheme">
 
1) a (currently) reduced set of functions:
Line 3,650:
 
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: dip swap '_ set execute _ ; : nip swap drop ;
: first 0 extract nip ; : second 1 extract nip ;
 
Line 3,671:
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1.
 
<syntaxhighlight lang="langur">var .hash = h{1: "abc", "1": 789}
 
# may assign with existing or non-existing hash key (if hash is mutable)
Line 3,692:
 
=={{header|Lasso}}==
<syntaxhighlight lang=Lasso"lasso">// In Lasso associative arrays are called maps
 
// Define an empty map
Line 3,732:
 
=={{header|LFE}}==
<syntaxhighlight lang="lisp">
(let* ((my-dict (: dict new))
(my-dict (: dict store 'key-1 '"value 1" my-dict))
Line 3,743:
=={{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 3,760:
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">props = [#key1: "value1", #key2: "value2"]
 
put props[#key2]
Line 3,773:
=={{header|LiveCode}}==
Livecode arrays are only associative, but can be accessed by ordinal if they are used as the key.
<syntaxhighlight lang=LiveCode"livecode">command assocArray
local tArray
put "value 1" into tArray["key 1"]
Line 3,784:
end assocArray</syntaxhighlight>
Output
<syntaxhighlight lang=LiveCode"livecode">number of elements: 3
length of item 3: 5
keys: key numbers
Line 3,792:
=={{header|Logo}}==
[[UCB Logo]] has "property lists" which associate names with values. They have their own namespace.
<syntaxhighlight lang="logo">pprop "animals "cat 5
pprop "animals "dog 4
pprop "animals "mouse 11
Line 3,801:
=={{header|LOLCODE}}==
BUKKITs are associative arrays
<syntaxhighlight lang="lolcode">HAI 1.2
I HAS A Hash ITZ A BUKKIT
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript
Line 3,813:
=={{header|Lua}}==
Lua tables are Hashes
<syntaxhighlight lang="lua">hash = {}
hash[ "key-1" ] = "val1"
hash[ "key-2" ] = 1
Line 3,821:
=={{header|M2000 Interpreter}}==
Μ2000 has Inventory object to use it as a Map. All keys converted to strings. If a key has no value then key is the value until we place one. A special type of Inventory is the Inventory Queue, where we can use same keys, and we can't delete except from the last append.
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There"
Print len(A)
Line 3,847:
=={{header|Maple}}==
Maple tables are hashed arrays. A table can be constructed by using the table constructor.
<syntaxhighlight lang=Maple"maple">> T := table( [ (2,3) = 4, "foo" = 1, sin(x) = cos(x) ] );
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4])
 
Line 3,859:
1</syntaxhighlight>
New entries are added by assignment.
<syntaxhighlight lang=Maple"maple">> T[ "bar" ] := 2;
T["bar"] := 2
 
Line 3,865:
2</syntaxhighlight>
Entries can be removed as follows.
<syntaxhighlight lang=Maple"maple">> T[ "foo" ] := evaln( T[ "foo" ] );
T["foo"] := T["foo"]
 
Line 3,873:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">a[2] = "string"; a["sometext"] = 23;</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 3,880:
Associative arrays are called structs. The following methods of creating hash are equivalent.
 
<syntaxhighlight lang=MATLAB"matlab"> hash.a = 1;
hash.b = 2;
hash.C = [3,4,5]; </syntaxhighlight>
alternatively
<syntaxhighlight lang=MATLAB"matlab"> hash = [];
hash = setfield(hash,'a',1);
hash = setfield(hash,'b',2);
hash = setfield(hash,'C',[3,4,5]); </syntaxhighlight>
or
<syntaxhighlight lang=MATLAB"matlab"> hash.('a') = 1;
hash.('b') = 2;
hash.('C') = [3,4,5]; </syntaxhighlight>
Line 3,905:
===MATLAB only: containers.Map===
Use of containers.Map removes some restrictions on key types that structs have. Keys can all be numeric or all be strings. Values can be of any type. Key and value types cannot be changed after creation of the containers.Map object.
<syntaxhighlight lang=MATLAB"matlab">m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</syntaxhighlight>
is equivalent to
<syntaxhighlight lang=MATLAB"matlab">m = containers.Map;
m('a') = 1;
m('b') = 2;
m('C') = 3;</syntaxhighlight>
since the KeyType defaults to 'char'. For numeric keys, the key and value types must be specified at creation.
<syntaxhighlight lang=MATLAB"matlab">m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</syntaxhighlight>
is equivalent to
<syntaxhighlight lang=MATLAB"matlab">m = containers.Map('KeyType', 'double', 'ValueType', 'any');
m(51) = 'fiftyone';
m(72) = 'seventytwo';
Line 3,933:
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">/* No need to declare anything, undeclared arrays are hashed */
 
h[1]: 6;
Line 3,943:
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">{1 :one 2 :two 3 :three}</syntaxhighlight>
 
=={{header|MiniScript}}==
A map literal in MiniScript is enclosed in curly braces, with key:value pairs separated by commas. Keys and values may be any type. Retrieval or assignment is by putting the key in square brackets. As syntactic sugar, when a string key follows the rules of a MiniScript identifier (starts with a letter and contains only letters, numbers, and underscores), you may also access it with dot syntax.
<syntaxhighlight lang=MiniScript"miniscript">map = { 3: "test", "foo": 42 }
 
print map[3]
Line 3,958:
=={{header|Nemerle}}==
This demonstrates two of several constructors, initializing the hashtable with a list of tuples or just specifying an initial capacity.
<syntaxhighlight lang=Nemerle"nemerle">using System;
using System.Console;
using Nemerle.Collections;
Line 3,977:
 
=={{header|NetRexx}}==
<syntaxhighlight lang=NetRexx"netrexx">/* NetRexx */
 
options replace format comments java crossref symbols
Line 3,997:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import tables
 
var
Line 4,045:
=={{header|Oberon-2}}==
{{works with| oo2c Version 2}}
<syntaxhighlight lang="oberon2">
MODULE AssociativeArray;
IMPORT
Line 4,094:
 
=== Associative map===
<syntaxhighlight lang="objeck">
# create map
map := StringMap->New();
Line 4,108:
 
===Hash table===
<syntaxhighlight lang="objeck">
# create map
map := StringHash->New();
Line 4,125:
 
You can use a NSDictionary to create an immutable hash. A dictionary can contain only objects; if you want store non objects like integer, you have to box it in NSNumber.
<syntaxhighlight lang="objc">NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"Joe Doe", @"name",
[NSNumber numberWithUnsignedInt:42], @"age",
Line 4,132:
 
The same as the above with the new literal syntax in clang 3.1+ / Apple LLVM Compiler 4.0+ (XCode 4.4+) :
<syntaxhighlight lang="objc">NSDictionary *dict = @{
@"name": @"Joe Doe",
@"age": @42,
Line 4,139:
 
To create a mutable dictionary, use NSMutableDictionary:
<syntaxhighlight lang="objc">NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:@"Joe Doe" forKey:@"name"];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"age"];</syntaxhighlight>
 
You can access value with objectForKey:. If a key does not exists, nil is returned.
<syntaxhighlight lang="objc">NSString *name = [dict objectForKey:@"name"];
unsigned age = [dict objectForKey:@"age"] unsignedIntValue];
id missing = [dict objectForKey:@"missing"];</syntaxhighlight>
Line 4,151:
===Hash table===
A simple idiom to create a hash table mapping strings to integers:
<syntaxhighlight lang="ocaml">let hash = Hashtbl.create 0;;
List.iter (fun (key, value) -> Hashtbl.add hash key value)
["foo", 5; "bar", 10; "baz", 15];;</syntaxhighlight>
To retrieve a value:
<syntaxhighlight lang="ocaml">let bar = Hashtbl.find hash "bar";; (* bar = 10 *)</syntaxhighlight>
To retrieve a value, returning a default if the key is not found:
<syntaxhighlight lang="ocaml">let quux = try Hashtbl.find hash "quux" with Not_found -> some_value;;</syntaxhighlight>
 
===Binary tree===
A simple idiom to create a persistent binary tree mapping strings to integers:
<syntaxhighlight lang="ocaml">module String = struct
type t = string
let compare = Pervasives.compare
Line 4,174:
;;</syntaxhighlight>
To retrieve a value:
<syntaxhighlight lang="ocaml">let bar = StringMap.find "bar" map;; (* bar = 10 *)</syntaxhighlight>
To retrieve a value, returning a default if the key is not found:
<syntaxhighlight lang="ocaml">let quux = try StringMap.find "quux" map with Not_found -> some_value;;</syntaxhighlight>
===Association list===
Some list functions allow you to use a list as an associative map, although the access time is O(N) so a Hashtbl or binary tree should be used for larger data-sets.
<syntaxhighlight lang=Ocaml"ocaml">let dict = ["foo", 5; "bar", 10; "baz", 15]
 
(* retrieve value *)
Line 4,192:
You can use only values as keys (atomic numbers, constants) and, as exception, symbols (symbols are references, but unique). No strings, lists, vectors and other objects can be used directly. In such cases use hashes or similar mechanisms.
 
<syntaxhighlight lang="scheme">
;;; empty associative array
#empty
Line 4,237:
 
Defining the map:
<syntaxhighlight lang=ooRexx"oorexx">map = .directory~new
map["foo"] = 5
map["bar"] = 10
Line 4,246:
 
Retrieving a value:
<syntaxhighlight lang=ooRexx"oorexx">item = map["foo"] -- => 6
item = map["invalid"] -- => .nil</syntaxhighlight>
Note that it is possible to put <code>.nil</code> as a value, so <code>.nil</code> being returned as a value is not sufficient for determining that the key is not in the collection. There is a <code>hasIndex</code> method for that.
 
Iterate over keys:
<syntaxhighlight lang=ooRexx"oorexx">loop key over map
say key
end
</syntaxhighlight>
Iterate over values:
<syntaxhighlight lang=ooRexx"oorexx">loop value over map~allItems
say value
end
</syntaxhighlight>
Iterate over key, value pairs:
<syntaxhighlight lang=ooRexx"oorexx">
s = map~supplier
loop while s~available
Line 4,271:
=={{header|OxygenBasic}}==
Not very efficient but the 'find' method could be optimised very easily.
<syntaxhighlight lang="oxygenbasic">
def n 200
 
Line 4,328:
=={{header|Oz}}==
A mutable map is called a 'dictionary' in Oz:
<syntaxhighlight lang="oz">declare
Dict = {Dictionary.new}
in
Line 4,339:
 
'Records' can be consideres immutable maps:
<syntaxhighlight lang="oz">declare
Rec = name(foo:5 bar:10 baz:20)
in
Line 4,348:
 
GP's associative arrays are called maps, and can be created like so:
<syntaxhighlight lang="parigp">M = Map();</syntaxhighlight>
They can be used as follows:
<syntaxhighlight lang="parigp">mapput(M, "key", "value");
mapput(M, 17, "different value");
mapput(M, "key2", Pi);
Line 4,362:
===Hash===
Definition:
<syntaxhighlight lang="perl"># using => key does not need to be quoted unless it contains special chars
my %hash = (
key1 => 'val1',
Line 4,379:
 
Use:
<syntaxhighlight lang="perl">print $hash{key1};
 
$hash{key1} = 'val1';
Line 4,386:
===HashRef===
Definition:
<syntaxhighlight lang="perl">my $hashref = {
key1 => 'val1',
'key-2' => 2,
Line 4,394:
 
Use:
<syntaxhighlight lang="perl">print $hashref->{key1};
 
$hashref->{key1} = 'val1';
Line 4,416:
integer tid=new_dict(), and pass that as an additional (final) parameter to the other routines (taking care not to miss
any). When you have no further use for it, an entire dictionary can be removed by invoking destroy_dict(tid).
<!--<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 4,429:
 
=={{header|Phixmonti}}==
<syntaxhighlight lang=Phixmonti"phixmonti">include ..\Utilitys.pmt
 
def getd /# dict key -- dict data #/
Line 4,466:
 
=={{header|PHP}}==
<syntaxhighlight lang="php">$array = array();
$array = []; // Simpler form of array initialization
$array['foo'] = 'bar';
Line 4,489:
 
===Iterate over key/value===
<syntaxhighlight lang="php">foreach($array as $key => $value)
{
echo "Key: $key Value: $value";
Line 4,496:
=={{header|Picat}}==
Associative arrays are called "map" in Picat.
<syntaxhighlight lang=Picat"picat">go =>
 
% Create an empty map
Line 4,551:
[http://software-lab.de/doc/refA.html#assoc association lists].
 
<syntaxhighlight lang=PicoLisp"picolisp">(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
Line 4,580:
''indices()'' and ''values()'' can be used to enumerate the contents
of an existing mapping.
<syntaxhighlight lang=Pike"pike">
mapping m = ([ "apple": "fruit", 17: "seventeen" ]);
write("indices: %O\nvalues: %O\n17: %O\n",
Line 4,602:
Since any data type can be used nested structures of arbitrary size can
be constructed.
<syntaxhighlight lang=Pike"pike">
mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]);
write("#ford: %O, #volvo: %O\n",
Line 4,614:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pli">*process source xref attributes or(!);
assocarr: Proc Options(main);
Dcl 1 aa,
Line 4,682:
 
The following example code is a "record definition", which has nothing to do with associative arrays:-
<syntaxhighlight lang=PL"pl/SQLsql">DECLARE
type ThisIsNotAnAssocArrayType is record (
myShape VARCHAR2(20),
Line 4,698:
 
=={{header|Pop11}}==
<syntaxhighlight lang="pop11">;;; Create expandable hash table of initial size 50 and with default
;;; value 0 (default value is returned when the item is absent).
vars ht = newmapping([], 50, 0, true);
Line 4,722:
 
=={{header|PostScript}}==
<syntaxhighlight lang="postscript">
<</a 100 /b 200 /c 300>>
dup /a get =
Line 4,728:
 
=={{header|Potion}}==
<syntaxhighlight lang="potion">mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff)
 
redblue = "purple"
Line 4,739:
=={{header|PowerShell}}==
An empty hash table can be created with:
<syntaxhighlight lang="powershell">$hashtable = @{}</syntaxhighlight>
A hash table can be initialized with key/value pairs:
<syntaxhighlight lang="powershell">$hashtable = @{
"key1" = "value 1"
key2 = 5 # if the key name has no spaces, no quotes are needed.
}</syntaxhighlight>
Individual values can be assigned or replaced by either using a property-style access method or indexing into the table with the given key:
<syntaxhighlight lang="powershell">$hashtable.foo = "bar"
$hashtable['bar'] = 42
$hashtable."a b" = 3.14 # keys can contain spaces, property-style access needs quotation marks, then
$hashtable[5] = 8 # keys don't need to be strings</syntaxhighlight>
NB. PowerShell compares strings as case-insensitive, that means the hashtable keys 'a' and 'A' are considered the same key. This happens when @{} is turned into a hashtable, but can be overridden by an explicit long-form:
<syntaxhighlight lang="powershell"># Case insensitive keys, both end up as the same key:
$h=@{}
$h['a'] = 1
Line 4,772:
a 1 </syntaxhighlight>
Similarly, values can be retrieved using either syntax:
<syntaxhighlight lang="powershell">$hashtable.key1 # value 1
$hashtable['key2'] # 5</syntaxhighlight>
It is common to see a hashtable literal used to create an object, by casting it to a new type:
<syntaxhighlight lang="powershell">$obj = [PSCustomObject]@{
"key1" = "value 1"
key2 = 5
Line 4,783:
=={{header|Prolog}}==
We use the facts table for this purpose.
<syntaxhighlight lang="prolog">
mymap(key1,value1).
mymap(key2,value2).
Line 4,794:
Hashes are a built-in type called Map in Purebasic.
 
<syntaxhighlight lang="purebasic">NewMap dict.s()
dict("country") = "Germany"
Debug dict("country")</syntaxhighlight>
Line 4,801:
Hashes are a built-in type called dictionaries (or mappings) in Python.
 
<syntaxhighlight lang="python">hash = dict() # 'dict' is the dictionary type.
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
hash = { 'key1':1, 'key2':2, }
Line 4,808:
Numerous methods exist for the mapping type https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
 
<syntaxhighlight lang="python"># empty dictionary
d = {}
d['spam'] = 1
Line 4,831:
Note: Python dictionary keys can be of any arbitrary "hashable" type. The following contains several distinct key value pairs:
 
<syntaxhighlight lang="python">myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }</syntaxhighlight>
 
(Some other languages such as ''awk'' and ''Perl'' evaluate all keys such that numerically or lexically equivalent expressions become identical entries in the hash or associative array).
Line 4,844:
=== 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"
> env[[index]]</syntaxhighlight>
<pre>[1] "rainfed hay"</pre>
<syntaxhighlight lang="r">> env[["1"]]</syntaxhighlight>
<pre>[1] "rainfed hay"</pre>
<syntaxhighlight lang="r">> env</syntaxhighlight>
<pre><environment: 0xb7cd560></pre>
<syntaxhighlight lang="r">> print(env)</syntaxhighlight>
<pre><environment: 0xb7cd560></pre>
 
=== vector example ===
 
<syntaxhighlight lang="r">> x <- c(hello=1, world=2, "!"=3)
> print(x)</syntaxhighlight>
<pre>hello world !
1 2 3</pre>
<syntaxhighlight lang="r">> print(names(x))</syntaxhighlight>
<pre>[1] "hello" "world" "!"</pre>
<syntaxhighlight lang="r">print(unname(x))</syntaxhighlight>
<pre>[1] 1 2 3</pre>
 
=== list example ===
 
<syntaxhighlight lang=R"r">> a <- list(a=1, b=2, c=3.14, d="xyz")
> print(a)</syntaxhighlight>
<pre>$a
Line 4,885:
$d
[1] "xyz"</pre>
<syntaxhighlight lang="r">> print(names(a))</syntaxhighlight>
<pre>[1] "a" "b" "c" "d"</pre>
<syntaxhighlight lang="r">> print(unname(a))</syntaxhighlight>
<pre>[[1]]
[1] 1
Line 4,903:
In Racket, hash tables are natively supported and encouraged over association lists in many cases. Data structures that behave like dictionaries support a unified interface.
 
<syntaxhighlight lang="racket">
#lang racket
 
Line 4,925:
The fatarrow, <code>=></code>, is no longer just a quoting comma; it now constructs a <code>Pair</code> object. But you can still define a hash with an ordinary list of even length.
 
<syntaxhighlight lang=perl6"raku" line>my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3';
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3';
 
Line 4,955:
 
=={{header|Raven}}==
<syntaxhighlight lang="raven">{ 'a' 1 'b' 2 'c' 3.14 'd' 'xyz' } as a_hash
a_hash print
 
Line 4,973:
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
relation key, value
insert "foo", "bar"
Line 5,005:
 
=={{header|Retro}}==
<syntaxhighlight lang=Retro"retro">with hashTable'
hashTable constant table
 
Line 5,017:
===version 1===
Associative arrays are called ''stem variables'' in Rexx.
<syntaxhighlight lang=Rexx"rexx">/* Rexx */
 
key0 = '0'
Line 5,032:
 
===version 2===
<syntaxhighlight lang="rexx">/*REXX program shows how to set/display values for an associative array.*/
/*┌────────────────────────────────────────────────────────────────────┐
│ The (below) two REXX statements aren't really necessary, but it │
Line 5,067:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project Associative array/Creation
 
Line 5,084:
=={{header|RLaB}}==
Associative arrays are called ''lists'' in RLaB.
<syntaxhighlight lang=RLaB"rlab">
x = <<>>; // create an empty list using strings as identifiers.
x.red = strtod("0xff0000"); // RLaB doesn't deal with hexadecimal numbers directly. Thus we
Line 5,114:
=={{header|Ruby}}==
A hash object that returns [[nil]] for unknown keys
<syntaxhighlight lang="ruby">hash={}
hash[666]='devil'
hash[777] # => nil
Line 5,120:
 
A hash object that returns 'unknown key' for unknown keys
<syntaxhighlight lang="ruby">hash=Hash.new('unknown key')
hash[666]='devil'
hash[777] # => 'unknown key'
Line 5,126:
 
A hash object that returns "unknown key #{key}" for unknown keys
<syntaxhighlight lang="ruby">hash=Hash.new{|h,k| "unknown key #{k}"}
hash[666]='devil'
hash[777] # => 'unknown key 777'
Line 5,132:
 
A hash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen
<syntaxhighlight lang="ruby">hash=Hash.new{|h,k|h[k]="key #{k} was added at #{Time.now}"}
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'
Line 5,138:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::HashMap;
fn main() {
let mut olympic_medals = HashMap::new();
Line 5,149:
 
=={{header|Sather}}==
<syntaxhighlight lang="sather">class MAIN is
main is
-- creation of a map between strings and integers
Line 5,172:
 
=={{header|Scala}}==
<syntaxhighlight lang=Scala"scala">// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
Line 5,179:
map.isDefinedAt(44) // true</syntaxhighlight>
 
<syntaxhighlight lang="scala">// mutable maps (HashSets)
import scala.collection.mutable.HashMap
val hash = new HashMap[Int, Int]
Line 5,190:
hash.contains(44) // true</syntaxhighlight>
 
<syntaxhighlight lang="scala">// iterate over key/value
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
// same with for syntax
for((k,v) <- hash) println("key " + k + " value " + v)</syntaxhighlight>
 
<syntaxhighlight lang="scala">// items in map where the key is greater than 3
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
// same with for syntax
Line 5,203:
 
Scheme has association lists (alists), which are inefficient, ordered maps with arbitrary keys and values.
<syntaxhighlight lang="scheme">(define my-dict '((a b) (1 hello) ("c" (a b c)))
(assoc 'a my-dict) ; evaluates to '(a b)</syntaxhighlight>
 
Line 5,209:
Hash tables are provided by SRFI-69 [http://srfi.schemers.org/srfi-69/srfi-69.html]. Many Scheme implementation also provide native hash tables.
 
<syntaxhighlight lang="scheme">(define my-alist '((a b) (1 hello) ("c" (a b c)))
(define my-hash (alist->hash-table my-alist))</syntaxhighlight>
 
The R6RS standard specifies support for hashtables in the [http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-14.html#node_chap_13 standard libraries] document.
 
<syntaxhighlight lang="scheme">#!r6rs
 
(import (rnrs base)
Line 5,236:
Associate arrays are not part of the Scheme language itself, but are compiler/interpreter or library add-ons. So I feel justified in presenting this sketch of yet another library add-on.
 
<syntaxhighlight lang="scheme">(cond-expand
(r7rs)
(chicken (import r7rs)))
Line 5,642:
Seed7 uses the type [http://seed7.sourceforge.net/manual/types.htm#hash hash] to support associative arrays.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
# Define hash type
Line 5,690:
=={{header|SenseTalk}}==
Associative arrays in SenseTalk are called property lists, or objects.
<syntaxhighlight lang="sensetalk">put {} into emptyPlist
put an empty property list into emptyPlist2
 
Line 5,706:
=={{header|SETL}}==
Associative arrays (referred to in SETL terminology as <i>maps</i>) are implemented as sets whose only members are tuples of length 2. Create such a set:
<syntaxhighlight lang="setl">m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};</syntaxhighlight>
We can then index the set, or map, with the first element of a constituent tuple to return that tuple's second element:
<syntaxhighlight lang="setl">print( m('bar') );</syntaxhighlight>
{{out}}
<pre>b</pre>
If the map might contain more than one value associated with the same key, we can return the set of them (in this instance a unit set because the keys are in fact unique):
<syntaxhighlight lang="setl">print( m{'bar'} );</syntaxhighlight>
{{out}}
<pre>{b}</pre>
 
=={{header|SETL4}}==
<syntaxhighlight lang=Setl4"setl4">
* Iterate over key-value pairs of a map
 
Line 5,745:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
Line 5,755:
=={{header|Slate}}==
<syntaxhighlight lang="slate">Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</syntaxhighlight>
 
=={{header|Smalltalk}}==
<syntaxhighlight lang="smalltalk">states := Dictionary new.
states at: 'MI' put: 'Michigan'.
states at: 'MN' put: 'Minnesota'.</syntaxhighlight>
alternative:
<syntaxhighlight lang="smalltalk">Dictionary withAssociations:{ 'MI' -> 'Michigan' . 'MN' -> 'Minnesota'}</syntaxhighlight>
 
=={{header|SNOBOL4}}==
<syntaxhighlight lang="snobol4"> t = table()
t<"red"> = "#ff0000"
t<"green"> = "#00ff00"
Line 5,776:
 
=={{header|SQL}}==
<syntaxhighlight lang=SQL"sql">
REM Create a table to associate keys with values
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .
Line 5,788:
{{works with|Db2 LUW}} version 9.7 or higher.
With SQL PL:
<syntaxhighlight lang="sql pl">
--#SET TERMINATOR @
 
Line 5,827:
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
a=asarray_create()
 
Line 5,847:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">// make an empty map
var a = [String: Int]()
// or
Line 5,863:
=={{header|Symsyn}}==
Symsyn implements Hash as a list of strings. Each name/value or key/value pair is stored in another string. The name/value pair is in the format 'name=value', the '=' is reserved.
<syntaxhighlight lang=Symsyn"symsyn">
#+ 'name=bob' $hash | add to hash
#? 'name' $hash $S | find 'name' and return 'bob' in $S
Line 5,871:
All arrays in Tcl are associative.
 
<syntaxhighlight lang="tcl"># Create one element at a time:
set hash(foo) 5
 
Line 5,892:
<br>
{{works with|Tcl|8.5}}
<syntaxhighlight lang="tcl"># Create in bulk
set d [dict create foo 5 bar 10 baz 15]
 
Line 5,916:
Toka provides associative arrays via a library.
 
<syntaxhighlight lang="toka">needs asarray
 
( create an associative array )
Line 5,933:
=={{header|UNIX Shell}}==
{{works with|ksh}}
<syntaxhighlight lang="bash">typeset -A hash
hash=( [key1]=val1 [key2]=val2 )
hash[key3]=val3
Line 5,940:
{{works with|bash}}
assigning values is the same as ksh, but to declare the variable as an associative array:
<syntaxhighlight lang="bash">declare -A hash</syntaxhighlight>
 
=={{header|UnixPipes}}==
A key value file can be considered as an associative array
<syntaxhighlight lang="bash">map='p.map'
 
function init() {
Line 5,991:
=={{header|Vala}}==
{{libheader|Gee}}
<syntaxhighlight lang="vala">
using Gee;
 
Line 6,016:
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key.
 
<syntaxhighlight lang="vb">Option Explicit
Sub Test()
Dim h As Object
Line 6,035:
=={{header|Vim Script}}==
Dictionary keys are always strings.
<syntaxhighlight lang="vim">" Creating a dictionary with some initial values
let dict = {"one": 1, "two": 2}
 
Line 6,058:
=={{header|Visual FoxPro}}==
Visual FoxPro has a collection class which can be used for this.
<syntaxhighlight lang="vfp">
LOCAL loCol As Collection, k, n, o
CLEAR
Line 6,101:
 
=={{header|Vlang}}==
<syntaxhighlight lang="vlang">fn main() {
// make empty map
mut my_map := map[string]int{}
Line 6,123:
 
=={{header|Wart}}==
<syntaxhighlight lang="wart">h <- (table 'a 1 'b 2)
h 'a
=> 1</syntaxhighlight>
Line 6,129:
=={{header|Wren}}==
Wren has a Map class built in.
<syntaxhighlight lang="ecmascript">var fruit = {} // creates an empty map
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[2] = "apple" // associates a key of 2 with "apple"
Line 6,162:
=={{header|XLISP}}==
XLISP refers to associative arrays as tables. The <tt>MAKE-TABLE</tt> function returns a new empty table, for instance:
<syntaxhighlight lang="lisp">(define starlings (make-table))</syntaxhighlight>
Values can then be inserted using <tt>TABLE-SET!</tt>:
<syntaxhighlight lang="lisp">(table-set! starlings "Common starling" "Sturnus vulgaris")
(table-set! starlings "Abbot's starling" "Poeoptera femoralis")
(table-set! starlings "Cape starling" "Lamprotornis nitens")</syntaxhighlight>
and retrieved using <tt>TABLE-REF</tt> with their keys:
<syntaxhighlight lang="lisp">(table-ref starlings "Cape starling")</syntaxhighlight>
Output in a REPL:
<pre>"Lamprotornis nitens"</pre>
Other functions provided for tables include <tt>MAP-OVER-TABLE-ENTRIES</tt>, which takes a table and a function of two arguments and applies the function to each entry (using the key and value as the two arguments), for instance:
<syntaxhighlight lang="lisp">(map-over-table-entries starlings (lambda (x y) (print (string-append x " (Linnaean name " y ")"))))</syntaxhighlight>
Output in a REPL:
<pre>"Abbott's starling (Linnaean name Poeoptera femoralis)"
Line 6,179:
 
=={{header|XPL0}}==
<syntaxhighlight lang=XPL0"xpl0">include c:\cxpl\stdlib;
char Dict(10,10);
int Entries;
Line 6,218:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">zkl: Dictionary("one",1, "two",2, "three",3)
D(two:2,three:3,one:1)
 
10,333

edits