Hash from two arrays: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 19: Line 19:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V keys = [‘a’, ‘b’, ‘c’]
<syntaxhighlight lang="11l">V keys = [‘a’, ‘b’, ‘c’]
V values = [1, 2, 3]
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
V hash_ = Dict(zip(keys, values))
print(hash_)</lang>
print(hash_)</syntaxhighlight>


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang actionscript>package
<syntaxhighlight lang="actionscript">package
{
{
public class MyClass
public class MyClass
Line 39: Line 39:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
{{works with|GNAT|GPL 2007}}
<lang ada>with Ada.Strings.Hash;
<syntaxhighlight lang="ada">with Ada.Strings.Hash;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
with Ada.Text_Io;
Line 85: Line 85:
end loop;
end loop;
end Hash_Map_Test;</lang>
end Hash_Map_Test;</syntaxhighlight>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Example:
Example:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#!/usr/bin/hopper
#!/usr/bin/hopper
#include <hopper.h>
#include <hopper.h>
Line 192: Line 192:
pause
pause
exit(0)
exit(0)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>Longitud HASH: 3
<pre>Longitud HASH: 3
Line 329: Line 329:
(Observation: some of these macros will be converted to libraries, due to their extension.)
(Observation: some of these macros will be converted to libraries, due to their extension.)


<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* macros HASH */
/* macros HASH */
#defn createhash(_X_) _X__KEY={#VOID},_X__HASH={#VOID}
#defn createhash(_X_) _X__KEY={#VOID},_X__HASH={#VOID}
Line 382: Line 382:
#define println {"\n"}print
#define println {"\n"}print


</syntaxhighlight>
</lang>


=={{header|Argile}}==
=={{header|Argile}}==
{{works with|Argile|1.1.0}}
{{works with|Argile|1.1.0}}
<lang Argile>use std, array, hash
<syntaxhighlight lang="argile">use std, array, hash


let keys = @["hexadecimal" "decimal" "octal" "binary"]
let keys = @["hexadecimal" "decimal" "octal" "binary"]
Line 393: Line 393:
for each val int i from 0 to 3
for each val int i from 0 to 3
hash[keys[i]] = values[i]
hash[keys[i]] = values[i]
del hash hash</lang>
del hash hash</syntaxhighlight>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
<syntaxhighlight lang="rebol">h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h</lang>
print h</syntaxhighlight>
{{out}}
{{out}}
Line 404: Line 404:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>array1 := ["two", "three", "apple"]
<syntaxhighlight lang="autohotkey">array1 := ["two", "three", "apple"]
array2 := [2, 3, "fruit"]
array2 := [2, 3, "fruit"]
hash := {}
hash := {}
Loop % array1.maxIndex()
Loop % array1.maxIndex()
hash[array1[A_Index]] := array2[A_Index]
hash[array1[A_Index]] := array2[A_Index]
MsgBox % hash["apple"] "`n" hash["two"]</lang>
MsgBox % hash["apple"] "`n" hash["two"]</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Awk arrays are used for both lists and hash maps.
Awk arrays are used for both lists and hash maps.
<!-- http://ideone.com/MsdNUc -->
<!-- http://ideone.com/MsdNUc -->
<lang awk># usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk
<syntaxhighlight lang="awk"># usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk
BEGIN {
BEGIN {
if(!list1) list1="one two three"
if(!list1) list1="one two three"
Line 424: Line 424:
for(i in c) print i,c[i]
for(i in c) print i,c[i]
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 438: Line 438:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
<syntaxhighlight lang="bbcbasic"> DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
Line 457: Line 457:
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</lang>
= MID$(dict$, I%, J% - I%)</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat> two three apple:?arr1
<syntaxhighlight lang="bracmat"> two three apple:?arr1
& 2 3 fruit:?arr2
& 2 3 fruit:?arr2
& new$hash:?H
& new$hash:?H
Line 470: Line 470:
& (H..forall)$out
& (H..forall)$out
& ;
& ;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>apple.fruit
<pre>apple.fruit
Line 477: Line 477:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>zip = { keys, values |
<syntaxhighlight lang="brat">zip = { keys, values |
h = [:]
h = [:]
keys.each_with_index { key, index |
keys.each_with_index { key, index |
Line 486: Line 486:
}
}


p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</lang>
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
Line 493: Line 493:
following implementation tries to be somewhat generic to facilitate using alternative key and
following implementation tries to be somewhat generic to facilitate using alternative key and
value types.
value types.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 607: Line 607:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
===C# 1.0===
===C# 1.0===
<lang csharp>static class Program
<syntaxhighlight lang="csharp">static class Program
{
{
static void Main()
static void Main()
Line 627: Line 627:
}
}
}
}
}</lang>
}</syntaxhighlight>


<code>Hashtable.Add</code> throws an exception when a key already exists.
<code>Hashtable.Add</code> throws an exception when a key already exists.


An alternative method to add entries is to use the indexer setter, which replaces the old value associated with a key, if any:
An alternative method to add entries is to use the indexer setter, which replaces the old value associated with a key, if any:
<lang csharp>h[keys[i]] = values[i];</lang>
<syntaxhighlight lang="csharp">h[keys[i]] = values[i];</syntaxhighlight>


===Modern===
===Modern===
Line 639: Line 639:
<code>Enumerable.Zip</code> truncates the longer of its arguments.
<code>Enumerable.Zip</code> truncates the longer of its arguments.


<lang csharp>using System.Linq;
<syntaxhighlight lang="csharp">using System.Linq;


static class Program
static class Program
Line 652: Line 652:
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <unordered_map>
<syntaxhighlight lang="cpp">#include <unordered_map>
#include <string>
#include <string>


Line 666: Line 666:
for( int i = 0 ; i < 3 ; i++ )
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
hash[ keys[i] ] = vals[i] ;
}</lang>
}</syntaxhighlight>


{{libheader|range-v3}}
{{libheader|range-v3}}
<lang cpp>#include <range/v3/view/zip.hpp>
<syntaxhighlight lang="cpp">#include <range/v3/view/zip.hpp>
#include <unordered_map>
#include <unordered_map>
#include <string>
#include <string>
Line 680: Line 680:
std::unordered_map<std::string, std::string> hash(ranges::view::zip(keys, vals));
std::unordered_map<std::string, std::string> hash(ranges::view::zip(keys, vals));
}
}
</syntaxhighlight>
</lang>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
value keys = [1, 2, 3];
value keys = [1, 2, 3];
value items = ['a', 'b', 'c'];
value items = ['a', 'b', 'c'];
value hash = map(zipEntries(keys, items));
value hash = map(zipEntries(keys, items));
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(zipmap [\a \b \c] [1 2 3])</lang>
<syntaxhighlight lang="lisp">(zipmap [\a \b \c] [1 2 3])</syntaxhighlight>


=={{header|Coco}}==
=={{header|Coco}}==
<lang coco>keys = <[apple banana orange grape]>
<syntaxhighlight lang="coco">keys = <[apple banana orange grape]>
values = <[red yellow orange purple]>
values = <[red yellow orange purple]>


object = new
object = new
@[keys[i]] = values[i] for i til keys.length</lang>
@[keys[i]] = values[i] for i til keys.length</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
keys = ['a','b','c']
keys = ['a','b','c']
values = [1,2,3]
values = [1,2,3]
map = {}
map = {}
map[key] = values[i] for key, i in keys
map[key] = values[i] for key, i in keys
</syntaxhighlight>
</lang>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<lang ColdFusion><cfscript>
<syntaxhighlight lang="coldfusion"><cfscript>
function makeHash(keyArray, valueArray) {
function makeHash(keyArray, valueArray) {
var x = 1;
var x = 1;
Line 721: Line 721:
valueArray = [1, 2, 3];
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
map = makeHash(keyArray, valueArray);
</cfscript></lang>
</cfscript></syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==


<lang lisp>(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
<syntaxhighlight lang="lisp">(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
(assert (= (length vector-1) (length vector-2)))
(assert (= (length vector-1) (length vector-2)))
(let ((table (make-hash-table :test test :size (length vector-1))))
(let ((table (make-hash-table :test test :size (length vector-1))))
(map nil (lambda (k v) (setf (gethash k table) v))
(map nil (lambda (k v) (setf (gethash k table) v))
vector-1 vector-2)
vector-1 vector-2)
table))</lang>
table))</syntaxhighlight>


Or, using cl:loop:
Or, using cl:loop:


<lang lisp>(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
<syntaxhighlight lang="lisp">(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
(loop initially (assert (= (length vector-1) (length vector-2)))
(loop initially (assert (= (length vector-1) (length vector-2)))
with table = (make-hash-table :test test :size (length vector-1))
with table = (make-hash-table :test test :size (length vector-1))
Line 740: Line 740:
for v across vector-2
for v across vector-2
do (setf (gethash k table) v)
do (setf (gethash k table) v)
finally (return table)))</lang>
finally (return table)))</syntaxhighlight>


In Common Lisp terminology, a vector is a one-dimensional array.
In Common Lisp terminology, a vector is a one-dimensional array.
Line 746: Line 746:
=={{header|Crystal}}==
=={{header|Crystal}}==


<lang ruby>keys = ('a'..'z').to_a # => a, b, c ... z
<syntaxhighlight lang="ruby">keys = ('a'..'z').to_a # => a, b, c ... z
vals = (1..26).to_a # => 1, 2, 3 ... 26
vals = (1..26).to_a # => 1, 2, 3 ... 26


hash = Hash.zip(keys, vals)
hash = Hash.zip(keys, vals)
p hash</lang>
p hash</syntaxhighlight>


<pre>
<pre>
Line 757: Line 757:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.array, std.range;
import std.array, std.range;


immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}</lang>
}</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>local :h_keys [ :one :two :three ]
<syntaxhighlight lang="dejavu">local :h_keys [ :one :two :three ]
local :h_values [ 1 2 3 ]
local :h_values [ 1 2 3 ]
local :h {}
local :h {}
for item in h_keys:
for item in h_keys:
set-to h item pop-from h_values
set-to h item pop-from h_values
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Hash_from_two_arrays;
program Hash_from_two_arrays;


Line 817: Line 817:
end.
end.


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 826: Line 826:
=={{header|Diego}}==
=={{header|Diego}}==
Diego has in-built <code>hash</code> and <code>dict</code> (short for 'dictionary') objects which function the same, except <code>hash</code> can only accept uuid datatypes for keys. Diego also has <code>hash_</code> verb and <code>_hash</code> posit, used to hash an object/command.
Diego has in-built <code>hash</code> and <code>dict</code> (short for 'dictionary') objects which function the same, except <code>hash</code> can only accept uuid datatypes for keys. Diego also has <code>hash_</code> verb and <code>_hash</code> posit, used to hash an object/command.
<lang diego>use_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();


add_ary(keysDict)_values(a,b,c);
add_ary(keysDict)_values(a,b,c);
Line 835: Line 835:
add_hash(aHash)_hash[valsDict]; // Keys will be new uuids
add_hash(aHash)_hash[valsDict]; // Keys will be new uuids


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


Arrays can manually be mapped from two arrays using a <code>_for</code> posit, for instance:
Arrays can manually be mapped from two arrays using a <code>_for</code> posit, for instance:
<lang diego>use_namespace(rosettacode)_me();
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();


add_dict(bDict);
add_dict(bDict);
Line 847: Line 847:
;
;


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


=={{header|E}}==
=={{header|E}}==


<lang e>def keys := ["one", "two", "three"]
<syntaxhighlight lang="e">def keys := ["one", "two", "three"]
def values := [1, 2, 3]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)</lang>
__makeMap.fromColumns(keys, values)</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'hash)
(lib 'hash)


Line 867: Line 867:
(hash-ref H 'elvis)
(hash-ref H 'elvis)
→ "the king"
→ "the king"
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> keys = [:one, :two, :three]
<syntaxhighlight lang="elixir">iex(1)> keys = [:one, :two, :three]
[:one, :two, :three]
[:one, :two, :three]
iex(2)> values = [1, 2, 3]
iex(2)> values = [1, 2, 3]
[1, 2, 3]
[1, 2, 3]
iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new)
iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new)
%{one: 1, three: 3, two: 2}</lang>
%{one: 1, three: 3, two: 2}</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).
</syntaxhighlight>
</lang>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)</lang>
<syntaxhighlight lang="fsharp">HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: hashtables ;
<syntaxhighlight lang="factor">USING: hashtables ;
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</lang>
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</syntaxhighlight>


=={{header|Falcon}}==
=={{header|Falcon}}==
<lang falcon>
<syntaxhighlight lang="falcon">
keys = [ 'a', 'b', 'c', 'd' ]
keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
hash = [ => ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]
</syntaxhighlight>
</lang>


=={{header|Fantom}}==
=={{header|Fantom}}==


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 916: Line 916:
}
}
}
}
</syntaxhighlight>
</lang>




=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>Dim As String keys(1 To 5) = {"1", "2", "3", "4", "5"}
<syntaxhighlight lang="freebasic">Dim As String keys(1 To 5) = {"1", "2", "3", "4", "5"}
Dim As String values(1 To 5) = {"one", "two", "three", "four", "five"}
Dim As String values(1 To 5) = {"one", "two", "three", "four", "five"}
Dim As String hash(Lbound(keys) To Ubound(keys))
Dim As String hash(Lbound(keys) To Ubound(keys))
Line 933: Line 933:
Print keys(i); " "; hash(i)'; " "; i
Print keys(i); " "; hash(i)'; " "; i
Next i
Next i
Sleep</lang>
Sleep</syntaxhighlight>
{{out}}
{{out}}
<pre> 1 one
<pre> 1 one
Line 944: Line 944:
=={{header|Frink}}==
=={{header|Frink}}==
There is a built-in dictionary/hash constructor that takes two arrays as input.
There is a built-in dictionary/hash constructor that takes two arrays as input.
<lang frink>
<syntaxhighlight lang="frink">
a = new dict[["a", "b", "c"], [1, 2, 3]]
a = new dict[["a", "b", "c"], [1, 2, 3]]
</syntaxhighlight>
</lang>


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=944f0b9cbf60910e7ee7ea4191928a7c Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=944f0b9cbf60910e7ee7ea4191928a7c Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Line 964: Line 964:
Next
Next


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 976: Line 976:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 988: Line 988:
}
}
fmt.Println(hash)
fmt.Println(hash)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 996: Line 996:
=={{header|Groovy}}==
=={{header|Groovy}}==


<lang groovy>def keys = ['a','b','c']
<syntaxhighlight lang="groovy">def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
def hash = [:]
keys.eachWithIndex { key, i ->
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
hash[key] = vals[i]
}</lang>
}</syntaxhighlight>


Alternative Version:
Alternative Version:
<lang groovy>List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }</lang>
<syntaxhighlight lang="groovy">List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }</syntaxhighlight>


Test:
Test:
<lang groovy>assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']</lang>
<syntaxhighlight lang="groovy">assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
<syntaxhighlight lang="visualfoxpro">LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
LOCAL hash := { => }
LOCAL hash := { => }
LOCAL i, j
LOCAL i, j
Line 1,016: Line 1,016:
FOR EACH i, j IN arr1, arr2
FOR EACH i, j IN arr1, arr2
hash[ i ] := j
hash[ i ] := j
NEXT</lang>
NEXT</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
{{works with|GHC|GHCi|6.6}}


<lang haskell>import Data.Map
<syntaxhighlight lang="haskell">import Data.Map


makeMap ks vs = fromList $ zip ks vs
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]</lang>
mymap = makeMap ['a','b','c'] [1,2,3]</syntaxhighlight>


=={{header|Huginn}}==
=={{header|Huginn}}==
<lang huginn>from Algorithms import materialize, zip;
<syntaxhighlight lang="huginn">from Algorithms import materialize, zip;


main() {
main() {
Line 1,033: Line 1,033:
values = ['a', 'b', 'c'];
values = ['a', 'b', 'c'];
hash = materialize( zip( key, values ), lookup );
hash = materialize( zip( key, values ), lookup );
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>link ximage # to format the structure
<syntaxhighlight lang="icon">link ximage # to format the structure


procedure main(arglist) #: demonstrate hash from 2 lists
procedure main(arglist) #: demonstrate hash from 2 lists
Line 1,047: Line 1,047:


write(ximage(T)) # show result
write(ximage(T)) # show result
end</lang>
end</syntaxhighlight>


=={{header|Ioke}}==
=={{header|Ioke}}==
<lang ioke>{} addKeysAndValues([:a, :b, :c], [1, 2, 3])</lang>
<syntaxhighlight lang="ioke">{} addKeysAndValues([:a, :b, :c], [1, 2, 3])</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
Line 1,058: Line 1,058:


'''Solution:'''
'''Solution:'''
<lang j>hash=: vals {~ keys&i.</lang>
<syntaxhighlight lang="j">hash=: vals {~ keys&i.</syntaxhighlight>
'''For example:'''
'''For example:'''


<lang j> keys=: 10?.100
<syntaxhighlight lang="j"> keys=: 10?.100
vals=: > ;:'zero one two three four five six seven eight nine'
vals=: > ;:'zero one two three four five six seven eight nine'
hash=: vals {~ keys&i.
hash=: vals {~ keys&i.
Line 1,079: Line 1,079:
six
six
seven
seven
two</lang>
two</syntaxhighlight>
Here,<code> keys </code>is a list of 10 integers between 0 and 99 chosen arbitrarily (we like to call this "randomly" but there is some mathematical controversy about implementations of randomness) without repetition, and<code> vals </code>is a 10 by 5 character matrix.
Here,<code> keys </code>is a list of 10 integers between 0 and 99 chosen arbitrarily (we like to call this "randomly" but there is some mathematical controversy about implementations of randomness) without repetition, and<code> vals </code>is a 10 by 5 character matrix.


=={{header|Java}}==
=={{header|Java}}==
<lang java>import java.util.HashMap;
<syntaxhighlight lang="java">import java.util.HashMap;
public static void main(String[] args){
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
String[] keys= {"a", "b", "c"};
Line 1,092: Line 1,092:
hash.put(keys[i], vals[i]);
hash.put(keys[i], vals[i]);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


===Iterative===
===Iterative===
<lang javascript>
<syntaxhighlight lang="javascript">
var keys = ['a', 'b', 'c'];
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var values = [1, 2, 3];
Line 1,104: Line 1,104:
map[ keys[i] ] = values[i];
map[ keys[i] ] = values[i];
}
}
</syntaxhighlight>
</lang>


===Iterative Using Foreach===
===Iterative Using Foreach===
<lang javascript>
<syntaxhighlight lang="javascript">
function arrToObj(keys, vals) {
function arrToObj(keys, vals) {
var map = {};
var map = {};
Line 1,115: Line 1,115:
return map;
return map;
}
}
</syntaxhighlight>
</lang>


===Using Reduce===
===Using Reduce===
<lang javascript>
<syntaxhighlight lang="javascript">
function arrToObj(keys, vals) {
function arrToObj(keys, vals) {
return keys.reduce(function(map, key, index) {
return keys.reduce(function(map, key, index) {
Line 1,125: Line 1,125:
}, {});
}, {});
}
}
</syntaxhighlight>
</lang>


=={{header|jq}}==
=={{header|jq}}==
jq only supports hashing of strings. In the following, accordingly, we assume that
jq only supports hashing of strings. In the following, accordingly, we assume that
one array (keys) is an array of strings.
one array (keys) is an array of strings.
<lang jq># hash(keys) creates a JSON object with the given keys as keys
<syntaxhighlight lang="jq"># hash(keys) creates a JSON object with the given keys as keys
# and values taken from the input array in turn.
# and values taken from the input array in turn.
# "keys" must be an array of strings.
# "keys" must be an array of strings.
Line 1,141: Line 1,141:
( {}; . + { (keys[$i]) : $values[$i] });
( {}; . + { (keys[$i]) : $values[$i] });


[1,2,3] | hash( ["a","b","c"] )</lang>
[1,2,3] | hash( ["a","b","c"] )</syntaxhighlight>
{{Out}}
{{Out}}
<lang jq>jq -n -f Hash_from_two_arrays.jq
<syntaxhighlight lang="jq">jq -n -f Hash_from_two_arrays.jq
{
{
"a": 1,
"a": 1,
"b": 2,
"b": 2,
"c": 3
"c": 3
}</lang>
}</syntaxhighlight>
To hash an array of distinct integers, the tostring filter can be used, e.g.
To hash an array of distinct integers, the tostring filter can be used, e.g.
[10,20,30] | hash( [1,2,3] | map(tostring) )
[10,20,30] | hash( [1,2,3] | map(tostring) )
yields:<lang jq>{
yields:<syntaxhighlight lang="jq">{
"1": 10,
"1": 10,
"2": 20,
"2": 20,
"3": 30
"3": 30
}</lang>
}</syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
From Javascript.
From Javascript.
<lang javascript>/* Hash from two arrays, in Jsish */
<syntaxhighlight lang="javascript">/* Hash from two arrays, in Jsish */
function hashTwo(k:array, v:array):object {
function hashTwo(k:array, v:array):object {
var hash = {};
var hash = {};
Line 1,178: Line 1,178:
hashTwo([], []) ==> {}
hashTwo([], []) ==> {}
=!EXPECTEND!=
=!EXPECTEND!=
*/</lang>
*/</syntaxhighlight>
{{out}}
{{out}}
<pre>prompt$ jsish -u hashTwo.jsi
<pre>prompt$ jsish -u hashTwo.jsi
Line 1,188: Line 1,188:


'''Using comprehension''':
'''Using comprehension''':
<lang julia>k = ["a", "b", "c"]
<syntaxhighlight lang="julia">k = ["a", "b", "c"]
v = [1, 2, 3]
v = [1, 2, 3]


Dict(ki => vi for (ki, vi) in zip(k, v))</lang>
Dict(ki => vi for (ki, vi) in zip(k, v))</syntaxhighlight>


'''Using constructor''':
'''Using constructor''':
<lang julia>Dict(zip(keys, values))</lang>
<syntaxhighlight lang="julia">Dict(zip(keys, values))</syntaxhighlight>


'''Specifying types''':
'''Specifying types''':
<lang julia>Dict{String,Int32}(zip(keys, values))</lang>
<syntaxhighlight lang="julia">Dict{String,Int32}(zip(keys, values))</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==
The keys in a dictionary must be a symbol.
The keys in a dictionary must be a symbol.
<lang K> a: `zero `one `two / symbols
<syntaxhighlight lang="k"> a: `zero `one `two / symbols
b: 0 1 2
b: 0 1 2


Line 1,210: Line 1,210:


d[`one]
d[`one]
1</lang>
1</syntaxhighlight>


Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols).
Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols).


<lang K> keys: !10 / 0..9
<syntaxhighlight lang="k"> keys: !10 / 0..9
split:{1_'(&x=y)_ x:y,x}
split:{1_'(&x=y)_ x:y,x}
vals:split["zero one two three four five six seven eight nine";" "]
vals:split["zero one two three four five six seven eight nine";" "]
Line 1,232: Line 1,232:


$d[s 1] / leading "$" converts back to string
$d[s 1] / leading "$" converts back to string
"one"</lang>
"one"</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.0
<syntaxhighlight lang="scala">// version 1.1.0


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,242: Line 1,242:
val hash = mapOf(*names.zip(ages).toTypedArray())
val hash = mapOf(*names.zip(ages).toTypedArray())
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,253: Line 1,253:


=={{header|Lang5}}==
=={{header|Lang5}}==
<lang lang5>: >table 2 compress -1 transpose ;
<syntaxhighlight lang="lang5">: >table 2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table</lang>
['one 'two 'three 'four] [1 2 3 4] >table</syntaxhighlight>


=={{header|langur}}==
=={{header|langur}}==
=== the easy way ===
=== the easy way ===
<lang langur>writeln toHash w/a b c d/, [1, 2, 3, 4]</lang>
<syntaxhighlight lang="langur">writeln toHash w/a b c d/, [1, 2, 3, 4]</syntaxhighlight>


Note that w/a b c d/ is a semantic convenience equivalent to ["a", "b", "c", "d"].
Note that w/a b c d/ is a semantic convenience equivalent to ["a", "b", "c", "d"].
Line 1,264: Line 1,264:
=== a longer way ===
=== a longer way ===
Using the append operator would silently overwrite hash values for matching keys, but the more() function will not.
Using the append operator would silently overwrite hash values for matching keys, but the more() function will not.
<lang langur>val .new = foldfrom(
<syntaxhighlight lang="langur">val .new = foldfrom(
f(.hash, .key, .value) more .hash, h{.key: .value},
f(.hash, .key, .value) more .hash, h{.key: .value},
h{}, w/a b c d/, [1, 2, 3, 4],
h{}, w/a b c d/, [1, 2, 3, 4],
)
)


writeln .new</lang>
writeln .new</syntaxhighlight>


{{out}}
{{out}}
Line 1,275: Line 1,275:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
array1 = array('a', 'b', 'c'),
array1 = array('a', 'b', 'c'),
array2 = array(1, 2, 3),
array2 = array(1, 2, 3),
Line 1,285: Line 1,285:
}
}


#hash</lang>
#hash</syntaxhighlight>
-> map(a = 1, b = 2, c = 3)
-> map(a = 1, b = 2, c = 3)


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>(let* ((keys (list 'foo 'bar 'baz))
<syntaxhighlight lang="lisp">(let* ((keys (list 'foo 'bar 'baz))
(vals (list '"foo data" '"bar data" '"baz data"))
(vals (list '"foo data" '"bar data" '"baz data"))
(tuples (: lists zipwith
(tuples (: lists zipwith
Line 1,295: Line 1,295:
(my-dict (: dict from_list tuples)))
(my-dict (: dict from_list tuples)))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>keys = ["a","b","c"]
<syntaxhighlight lang="lingo">keys = ["a","b","c"]
values = [1,2,3]
values = [1,2,3]


Line 1,308: Line 1,308:


put props
put props
-- ["a": 1, "b": 2, "c": 3]</lang>
-- ["a": 1, "b": 2, "c": 3]</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang LiveCode>put "a,b,c" into list1
<syntaxhighlight lang="livecode">put "a,b,c" into list1
put 10,20,30 into list2
put 10,20,30 into list2
split list1 using comma
split list1 using comma
Line 1,322: Line 1,322:


-- ouput
-- ouput
-- a:10,b:20,c:30</lang>
-- a:10,b:20,c:30</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function(keys,values)
<syntaxhighlight lang="lua">function(keys,values)
local t = {}
local t = {}
for i=1, #keys do
for i=1, #keys do
t[keys[i]] = values[i]
t[keys[i]] = values[i]
end
end
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckAll {
Module CheckAll {
Module CheckVectorType {
Module CheckVectorType {
Line 1,359: Line 1,359:
}
}
CheckAll
CheckAll
</syntaxhighlight>
</lang>


This is the real task, using two arrays as arguments in a function which return the hash table (an inventory object). Each pair has a key and a stack object. If a key found more than one we simply add to stack (at the bottom using Data - or at the top using Push). A module PrintKeyItems get the hash, the key to find, and the second array with values, and apply indexes from hash to array. The MakeHash add indexes using start value of array of values. So we can pass arrays with different start and end index, but they must be one dimension and have same number of items, else we get error
This is the real task, using two arrays as arguments in a function which return the hash table (an inventory object). Each pair has a key and a stack object. If a key found more than one we simply add to stack (at the bottom using Data - or at the top using Push). A module PrintKeyItems get the hash, the key to find, and the second array with values, and apply indexes from hash to array. The MakeHash add indexes using start value of array of values. So we can pass arrays with different start and end index, but they must be one dimension and have same number of items, else we get error




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Module Checkit {
Function MakeHash(&a$(), &b$()) {
Function MakeHash(&a$(), &b$()) {
Line 1,406: Line 1,406:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>A := [1, 2, 3];
<syntaxhighlight lang="maple">A := [1, 2, 3];
B := ["one", "two", three"];
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );</lang>
T := table( zip( `=`, A, B ) );</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
<syntaxhighlight lang="mathematica">Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]


Line 1,420: Line 1,420:
->Hash[1]=one
->Hash[1]=one
->Hash[2]=two
->Hash[2]=two
->Hash[3]=three</lang>
->Hash[3]=three</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
See [[Associative arrays/Creation#MATLAB_.2F_Octave|Associative arrays/Creation]] for clarification of limitations and differences between the two methods.
See [[Associative arrays/Creation#MATLAB_.2F_Octave|Associative arrays/Creation]] for clarification of limitations and differences between the two methods.
===MATLAB/Octave: structs===
===MATLAB/Octave: structs===
<lang MATLAB>function s = StructFromArrays(allKeys, allVals)
<syntaxhighlight lang="matlab">function s = StructFromArrays(allKeys, allVals)
% allKeys must be cell array of strings of valid field-names
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
% allVals can be cell array or array of numbers
Line 1,439: Line 1,439:
end
end
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27])
<pre>>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27])
Line 1,465: Line 1,465:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>keys = ["foo", "bar", "val"]
<syntaxhighlight lang="miniscript">keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]
values = ["little", "miss", "muffet"]


Line 1,473: Line 1,473:
end for
end for


print d</lang>
print d</syntaxhighlight>
{{out}}
{{out}}
<pre>{"bar": "miss", "foo": "little", "val": "muffet"}</pre>
<pre>{"bar": "miss", "foo": "little", "val": "muffet"}</pre>


=={{header|Neko}}==
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
**/
Line 1,497: Line 1,497:
*/
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)</lang>
$hiter(table, show)</syntaxhighlight>


{{out}}
{{out}}
Line 1,509: Line 1,509:


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections;
Line 1,524: Line 1,524:
WriteLine("{0}: {1}", item.Key, item.Value);
WriteLine("{0}: {1}", item.Key, item.Value);
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
=== REXX Style ===
=== REXX Style ===
{{trans|REXX}}
{{trans|REXX}}
<lang netrexx>/* NetRexx program ****************************************************
<syntaxhighlight lang="netrexx">/* NetRexx program ****************************************************
* 04.11.2012 Walter Pachl derived from REXX
* 04.11.2012 Walter Pachl derived from REXX
**********************************************************************/
**********************************************************************/
Line 1,550: Line 1,550:
Say ' 'keys
Say ' 'keys
Parse Ask z
Parse Ask z
Say z '->' value[z]</lang>
Say z '->' value[z]</syntaxhighlight>


=== Java Collections ===
=== Java Collections ===
NetRexx has access to Java's Collection objects too.
NetRexx has access to Java's Collection objects too.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,595: Line 1,595:


return
return
</syntaxhighlight>
</lang>


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


let keys = @['a','b','c']
let keys = @['a','b','c']
let values = @[1, 2, 3]
let values = @[1, 2, 3]


let table = toTable zip(keys, values)</lang>
let table = toTable zip(keys, values)</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
Works with oo2c version 2
Works with oo2c version 2
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE HashFromArrays;
MODULE HashFromArrays;
IMPORT
IMPORT
Line 1,643: Line 1,643:
Do;
Do;
END HashFromArrays.
END HashFromArrays.
</syntaxhighlight>
</lang>


=={{header|Objeck}}==
=={{header|Objeck}}==


<lang objeck>
<syntaxhighlight lang="objeck">
use Structure;
use Structure;


Line 1,662: Line 1,662:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==


<lang objc>NSArray *keys = @[@"a", @"b", @"c"];
<syntaxhighlight lang="objc">NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</lang>
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
The idiomatic solution uses lists rather than arrays.
The idiomatic solution uses lists rather than arrays.


<lang ocaml>let keys = [ "foo"; "bar"; "baz" ]
<syntaxhighlight lang="ocaml">let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;
and hash = Hashtbl.create 0;;


List.iter2 (Hashtbl.add hash) keys vals;;</lang>
List.iter2 (Hashtbl.add hash) keys vals;;</syntaxhighlight>


The solution is similar with arrays.
The solution is similar with arrays.


<lang ocaml>let keys = [| "foo"; "bar"; "baz" |]
<syntaxhighlight lang="ocaml">let keys = [| "foo"; "bar"; "baz" |]
and vals = [| 16384; 32768; 65536 |]
and vals = [| 16384; 32768; 65536 |]
and hash = Hashtbl.create 0;;
and hash = Hashtbl.create 0;;


Array.iter2 (Hashtbl.add hash) keys vals;;</lang>
Array.iter2 (Hashtbl.add hash) keys vals;;</syntaxhighlight>


In either case, an exception is raised if the inputs are different lengths.
In either case, an exception is raised if the inputs are different lengths.
Line 1,691: Line 1,691:
If you want to use functional binary search trees instead of hash tables:
If you want to use functional binary search trees instead of hash tables:


<lang ocaml>module StringMap = Map.Make (String);;
<syntaxhighlight lang="ocaml">module StringMap = Map.Make (String);;


let keys = [ "foo"; "bar"; "baz" ]
let keys = [ "foo"; "bar"; "baz" ]
Line 1,697: Line 1,697:
and map = StringMap.empty;;
and map = StringMap.empty;;


let map = List.fold_right2 StringMap.add keys vals map;;</lang>
let map = List.fold_right2 StringMap.add keys vals map;;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>array1 = .array~of("Rick", "Mike", "David")
<syntaxhighlight lang="oorexx">array1 = .array~of("Rick", "Mike", "David")
array2 = .array~of("555-9862", "555-5309", "555-6666")
array2 = .array~of("555-9862", "555-5309", "555-6666")


Line 1,712: Line 1,712:
Say 'Enter a name'
Say 'Enter a name'
Parse Pull name
Parse Pull name
Say name '->' hash[name]</lang>
Say name '->' hash[name]</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a name
<pre>Enter a name
Line 1,719: Line 1,719:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {ZipRecord Keys Values}
fun {ZipRecord Keys Values}
{List.toRecord unit {List.zip Keys Values MakePair}}
{List.toRecord unit {List.zip Keys Values MakePair}}
Line 1,728: Line 1,728:
end
end
in
in
{Show {ZipRecord [a b c] [1 2 3]}}</lang>
{Show {ZipRecord [a b c] [1 2 3]}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==


<lang parigp>hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));</lang>
<syntaxhighlight lang="parigp">hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
{{libheader|contnrs}}
{{libheader|contnrs}}
<lang pascal>program HashFromTwoArrays (Output);
<syntaxhighlight lang="pascal">program HashFromTwoArrays (Output);


uses
uses
Line 1,754: Line 1,754:
writeln ('Length of hash table: ', hash.Count);
writeln ('Length of hash table: ', hash.Count);
hash.Destroy;
hash.Destroy;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>% ./HashFromTwoArrays
<pre>% ./HashFromTwoArrays
Line 1,761: Line 1,761:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my @keys = qw(a b c);
<syntaxhighlight lang="perl">my @keys = qw(a b c);
my @vals = (1, 2, 3);
my @vals = (1, 2, 3);
my %hash;
my %hash;
@hash{@keys} = @vals;</lang>
@hash{@keys} = @vals;</syntaxhighlight>


Alternatively, using {{libheader|List::MoreUtils}}:
Alternatively, using {{libheader|List::MoreUtils}}:


<lang perl>use List::MoreUtils qw(zip);
<syntaxhighlight lang="perl">use List::MoreUtils qw(zip);
my %hash = zip @keys, @vals;</lang>
my %hash = zip @keys, @vals;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out.
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">make_hash</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">keyarray</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">valuearray</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">make_hash</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">keyarray</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">valuearray</span><span style="color: #0000FF;">)</span>
Line 1,791: Line 1,791:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dict</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dict</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--?valuearray[getd(1,dict)]</span>
<span style="color: #000080;font-style:italic;">--?valuearray[getd(1,dict)]</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,800: Line 1,800:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt


def getd /# array key -- array data #/
def getd /# array key -- array data #/
Line 1,816: Line 1,816:
"two" getd print nl
"two" getd print nl
PI getd tostr print nl
PI getd tostr print nl
3 getd print</lang>
3 getd print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,827: Line 1,827:
=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|5}}
{{works with|PHP|5}}
<lang php>$keys = array('a', 'b', 'c');
<syntaxhighlight lang="php">$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);</lang>
$hash = array_combine($keys, $values);</syntaxhighlight>


{{works with|PHP|4}}
{{works with|PHP|4}}
<lang php>$keys = array('a', 'b', 'c');
<syntaxhighlight lang="php">$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$values = array(1, 2, 3);
$hash = array();
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
$hash[$keys[$idx]] = $values[$idx];
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
A = [a,b,c,d,e],
A = [a,b,c,d,e],
B = [1,2,3,4,5],
B = [1,2,3,4,5],
Map = new_map([K=V : {K,V} in zip(A,B)]),
Map = new_map([K=V : {K,V} in zip(A,B)]),
println(Map).</lang>
println(Map).</syntaxhighlight>


{{out}}
{{out}}
Line 1,851: Line 1,851:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(let (Keys '(one two three) Values (1 2 3))
<syntaxhighlight lang="picolisp">(let (Keys '(one two three) Values (1 2 3))
(mapc println
(mapc println
(mapcar cons Keys Values) ) )</lang>
(mapcar cons Keys Values) ) )</syntaxhighlight>
{{out}}
{{out}}
<pre>(one . 1)
<pre>(one . 1)
Line 1,861: Line 1,861:
=={{header|Pike}}==
=={{header|Pike}}==
Any data type can be used as indices (keys) and values.
Any data type can be used as indices (keys) and values.
<syntaxhighlight lang="pike">
<lang Pike>
array indices = ({ "a", "b", 42 });
array indices = ({ "a", "b", 42 });
array values = ({ Image.Color(0,0,0), "hello", "world" });
array values = ({ Image.Color(0,0,0), "hello", "world" });
mapping m = mkmapping( indices, values );
mapping m = mkmapping( indices, values );
write("%O\n", m);
write("%O\n", m);
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,878: Line 1,878:
=={{header|Pop11}}==
=={{header|Pop11}}==


<lang pop11>vars keys = { 1 a b c};
<syntaxhighlight lang="pop11">vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars vals = { 2 3 valb valc};
vars i;
vars i;
Line 1,886: Line 1,886:
for i from 1 to length(keys) do
for i from 1 to length(keys) do
vals(i) -> ht(keys(i));
vals(i) -> ht(keys(i));
endfor;</lang>
endfor;</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<syntaxhighlight lang="postscript">
% push our arrays
% push our arrays
[/a /b /c /d /e] [1 2 3 4 5]
[/a /b /c /d /e] [1 2 3 4 5]
Line 1,897: Line 1,897:
% show that we have created the hash
% show that we have created the hash
{= =} forall
{= =} forall
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>function create_hash ([array] $keys, [array] $values) {
<syntaxhighlight lang="powershell">function create_hash ([array] $keys, [array] $values) {
$h = @{}
$h = @{}
if ($keys.Length -ne $values.Length) {
if ($keys.Length -ne $values.Length) {
Line 1,912: Line 1,912:
}
}
return $h
return $h
}</lang>
}</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==


<lang prolog>% this one with side effect hash table creation
<syntaxhighlight lang="prolog">% this one with side effect hash table creation


:-dynamic hash/2.
:-dynamic hash/2.
Line 1,934: Line 1,934:
make_hash_pure(Q,Q1,R).
make_hash_pure(Q,Q1,R).


:-make_hash_pure([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]],L),findall(M,(member(M,L),assert(M)),L).</lang>
:-make_hash_pure([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]],L),findall(M,(member(M,L),assert(M)),L).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Dim keys.s(3)
<syntaxhighlight lang="purebasic">Dim keys.s(3)
Dim vals.s(3)
Dim vals.s(3)
NewMap Hash.s()
NewMap Hash.s()
Line 1,948: Line 1,948:
ForEach Hash()
ForEach Hash()
Debug Hash()
Debug Hash()
Next</lang>
Next</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|3.0+ and 2.7}}
{{works with|Python|3.0+ and 2.7}}
Shows off the dict comprehensions in Python 3 (that were back-ported to 2.7):
Shows off the dict comprehensions in Python 3 (that were back-ported to 2.7):
<lang python>keys = ['a', 'b', 'c']
<syntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}</lang>
hash = {key: value for key, value in zip(keys, values)}</syntaxhighlight>


{{works with|Python|2.2+}}
{{works with|Python|2.2+}}
<lang python>keys = ['a', 'b', 'c']
<syntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
values = [1, 2, 3]
hash = dict(zip(keys, values))
hash = dict(zip(keys, values))
Line 1,964: Line 1,964:
# Lazily, Python 2.3+, not 3.x:
# Lazily, Python 2.3+, not 3.x:
from itertools import izip
from itertools import izip
hash = dict(izip(keys, values))</lang>
hash = dict(izip(keys, values))</syntaxhighlight>


{{works with|Python|2.0+}}
{{works with|Python|2.0+}}
<lang python>keys = ['a', 'b', 'c']
<syntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
values = [1, 2, 3]
hash = {}
hash = {}
for k,v in zip(keys, values):
for k,v in zip(keys, values):
hash[k] = v</lang>
hash[k] = v</syntaxhighlight>


The original (Ruby) example uses a range of different types as keys. Here is similar in python (run at the shell):
The original (Ruby) example uses a range of different types as keys. Here is similar in python (run at the shell):
<lang python>>>> class Hashable(object):
<syntaxhighlight lang="python">>>> class Hashable(object):
def __hash__(self):
def __hash__(self):
return id(self) ^ 0xBEEF
return id(self) ^ 0xBEEF
Line 2,014: Line 2,014:
<__main__.Hashable object at 0x012AFC50> : 0
<__main__.Hashable object at 0x012AFC50> : 0
>>> # Notice that the key "True" disappeared, and its value got associated with the key "1"
>>> # Notice that the key "True" disappeared, and its value got associated with the key "1"
>>> # This is because 1 == True in Python, and dictionaries cannot have two equal keys</lang>
>>> # This is because 1 == True in Python, and dictionaries cannot have two equal keys</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
Assuming that the keys are coercible to character form, we can simply use the names attribute to create a hash. This example is taken from the [[wp:Hash_table#Separate_chaining|Wikipedia page on hash tables]].
Assuming that the keys are coercible to character form, we can simply use the names attribute to create a hash. This example is taken from the [[wp:Hash_table#Separate_chaining|Wikipedia page on hash tables]].
<lang r># Set up hash table
<syntaxhighlight lang="r"># Set up hash table
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
values <- c(152, 1, 254, 152, 153)
Line 2,025: Line 2,025:
values["Sam Doe"] # vals["Sam Doe"]
values["Sam Doe"] # vals["Sam Doe"]
# Get all keys corresponding to a value
# Get all keys corresponding to a value
names(values)[values==152] # "John Smith" "Sandra Dee"</lang>
names(values)[values==152] # "John Smith" "Sandra Dee"</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
(make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))</lang>
(make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))</syntaxhighlight>


Alternatively:
Alternatively:
<lang racket>
<syntaxhighlight lang="racket">
(define (connect keys vals) (for/hash ([k keys] [v vals]) (values k v)))
(define (connect keys vals) (for/hash ([k keys] [v vals]) (values k v)))
;; Example:
;; Example:
(connect #("a" "b" "c" "d") #(1 2 3 4))
(connect #("a" "b" "c" "d") #(1 2 3 4))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,044: Line 2,044:


{{works with|rakudo|2018.03}}
{{works with|rakudo|2018.03}}
<lang perl6>my @keys = <a b c d e>;
<syntaxhighlight lang="raku" line>my @keys = <a b c d e>;
my @values = ^5;
my @values = ^5;


Line 2,062: Line 2,062:


quietly # suppress warnings about unused hash
quietly # suppress warnings about unused hash
{ @keys »=>« @values }; # Will fail if the lists differ in length</lang>
{ @keys »=>« @values }; # Will fail if the lists differ in length</syntaxhighlight>


=={{header|Raven}}==
=={{header|Raven}}==


<lang raven>[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals
<syntaxhighlight lang="raven">[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals
$keys $vals combine as $hash</lang>
$keys $vals combine as $hash</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
This REXX version allows multiple keys for a value, &nbsp; the keys are case sensitive.
This REXX version allows multiple keys for a value, &nbsp; the keys are case sensitive.
<lang rexx>/*REXX program demonstrates hashing of a stemmed array (from a key or multiple keys)*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates hashing of a stemmed array (from a key or multiple keys)*/
key.= /*names of the nine regular polygons. */
key.= /*names of the nine regular polygons. */
vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon'
vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon'
Line 2,093: Line 2,093:
hash.map= word(@val, j)
hash.map= word(@val, j)
end /*j*/
end /*j*/
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the input value of: &nbsp; &nbsp; <tt> phive </tt>}}
{{out|output|text=&nbsp; when using the input value of: &nbsp; &nbsp; <tt> phive </tt>}}
<pre>
<pre>
Line 2,104: Line 2,104:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Hash from two arrays
# Project : Hash from two arrays


Line 2,119: Line 2,119:
see c[i] + " " + i + nl
see c[i] + " " + i + nl
next
next
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,128: Line 2,128:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>
<syntaxhighlight lang="ruby">
keys = ['hal',666,[1,2,3]]
keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]
vals = ['ibm','devil',123]
Line 2,138: Line 2,138:
#retrieve the value linked to the key [1,2,3]
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123
puts hash[ [1,2,3] ] # => 123
</syntaxhighlight>
</lang>


In Ruby 2.1 the method "to_h" was introduced:
In Ruby 2.1 the method "to_h" was introduced:
<lang ruby>keys = ['hal', 666, [1,2,3]]
<syntaxhighlight lang="ruby">keys = ['hal', 666, [1,2,3]]
vals = ['ibm', 'devil', 123]
vals = ['ibm', 'devil', 123]


keys.zip(vals).to_h</lang>
keys.zip(vals).to_h</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::collections::HashMap;
<syntaxhighlight lang="rust">use std::collections::HashMap;


fn main() {
fn main() {
Line 2,155: Line 2,155:
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
println!("{:?}", hash);
}</lang>
}</syntaxhighlight>


=={{header|Sather}}==
=={{header|Sather}}==
<lang sather>class ZIPPER{K,E} is
<syntaxhighlight lang="sather">class ZIPPER{K,E} is
zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
pre k.size = e.size
pre k.size = e.size
Line 2,180: Line 2,180:
end;
end;


end;</lang>
end;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val keys = List(1, 2, 3)
<syntaxhighlight lang="scala">val keys = List(1, 2, 3)
val values = Array("A", "B", "C") // Array mixed with List
val values = Array("A", "B", "C") // Array mixed with List
val map = keys.zip(values).toMap // and other Seq are possible.
val map = keys.zip(values).toMap // and other Seq are possible.
Line 2,189: Line 2,189:
// Testing
// Testing
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
println("Successfully completed without errors.")</lang>
println("Successfully completed without errors.")</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
=== Using [http://srfi.schemers.org/srfi-69/srfi-69.html SRFI 69] ===
=== Using [http://srfi.schemers.org/srfi-69/srfi-69.html SRFI 69] ===
<lang scheme>(define (lists->hash-table keys values . rest)
<syntaxhighlight lang="scheme">(define (lists->hash-table keys values . rest)
(apply alist->hash-table (map cons keys values) rest))</lang>
(apply alist->hash-table (map cons keys values) rest))</syntaxhighlight>


=== Using association lists ===
=== Using association lists ===
<lang scheme>;; Using SRFI-1, R6RS, or R7RS association lists.
<syntaxhighlight lang="scheme">;; Using SRFI-1, R6RS, or R7RS association lists.


;; Because the task calls for ‘arrays’, I start with actual arrays
;; Because the task calls for ‘arrays’, I start with actual arrays
Line 2,219: Line 2,219:
;; ("b" . 2)
;; ("b" . 2)
;; ("d" . 4)
;; ("d" . 4)
;;</lang>
;;</syntaxhighlight>


=== Using [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] ===
=== Using [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] ===
Line 2,225: Line 2,225:
You need to compile this code along with the [[Associative_array/Creation#A_persistent_associative_array_from_scratch|persistent associative arrays]] code. And, yes, the hash function for that implementation ''can'' return floating point numbers, the way the one here does.
You need to compile this code along with the [[Associative_array/Creation#A_persistent_associative_array_from_scratch|persistent associative arrays]] code. And, yes, the hash function for that implementation ''can'' return floating point numbers, the way the one here does.


<lang scheme>(import (associative-arrays))
<syntaxhighlight lang="scheme">(import (associative-arrays))


;; Because the task calls for ‘arrays’, I start with actual arrays
;; Because the task calls for ‘arrays’, I start with actual arrays
Line 2,255: Line 2,255:
;;
;;
;; Looking up "b" and "d": 2 4
;; Looking up "b" and "d": 2 4
;;</lang>
;;</syntaxhighlight>


Side note: association lists can be used in either a persistent or non-persistent manner.
Side note: association lists can be used in either a persistent or non-persistent manner.
Line 2,261: Line 2,261:
=={{header|Seed7}}==
=={{header|Seed7}}==


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


const type: numericHash is hash [string] integer;
const type: numericHash is hash [string] integer;
Line 2,275: Line 2,275:
myHash @:= [keyList[number]] valueList[number];
myHash @:= [keyList[number]] valueList[number];
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
set keyList to ["red", "green", "blue"]
set keyList to ["red", "green", "blue"]
set valueList to [150,0,128]
set valueList to [150,0,128]
Line 2,289: Line 2,289:
--> (blue:"128", green:"0", red:"150")
--> (blue:"128", green:"0", red:"150")


</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var keys = %w(a b c)
<syntaxhighlight lang="ruby">var keys = %w(a b c)
var vals = [1, 2, 3]
var vals = [1, 2, 3]


var hash = Hash()
var hash = Hash()
hash{keys...} = vals...
hash{keys...} = vals...
say hash</lang>
say hash</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}


<lang smalltalk>Array extend [
<syntaxhighlight lang="smalltalk">Array extend [
dictionaryWithValues: array [ |d|
dictionaryWithValues: array [ |d|
d := Dictionary new.
d := Dictionary new.
Line 2,314: Line 2,314:


({ 'red' . 'one' . 'two' }
({ 'red' . 'one' . 'two' }
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</lang>
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</syntaxhighlight>


{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
{{works with|VisualWorks Smalltalk}}
<lang smalltalk>Dictionary
<syntaxhighlight lang="smalltalk">Dictionary
withKeys:#('one' 'two' 'three')
withKeys:#('one' 'two' 'three')
andValues:#('eins' 'zwei' 'drei')</lang>
andValues:#('eins' 'zwei' 'drei')</syntaxhighlight>


{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>Dictionary withAssociations:{ 'one'->1 . 'two'->2 . 'three'->3 }</lang>
<syntaxhighlight lang="smalltalk">Dictionary withAssociations:{ 'one'->1 . 'two'->2 . 'three'->3 }</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
Line 2,331: Line 2,331:
{{works with|CSnobol}}
{{works with|CSnobol}}


<lang SNOBOL4>* # Fill arrays
<syntaxhighlight lang="snobol4">* # Fill arrays
keys = array(5); vals = array(5)
keys = array(5); vals = array(5)
ks = 'ABCDE'; vs = '12345'
ks = 'ABCDE'; vs = '12345'
Line 2,346: Line 2,346:
str = str ch ':' hash<ch> ' ' :(tloop)
str = str ch ':' hash<ch> ' ' :(tloop)
out output = str
out output = str
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 2,352: Line 2,352:


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>let keys = { "foo", "bar", "baz" };
<syntaxhighlight lang="sparkling">let keys = { "foo", "bar", "baz" };
let vals = { 13, 37, 42 };
let vals = { 13, 37, 42 };
var hash = {};
var hash = {};
for var i = 0; i < sizeof keys; i++ {
for var i = 0; i < sizeof keys; i++ {
hash[keys[i]] = vals[i];
hash[keys[i]] = vals[i];
}</lang>
}</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
Line 2,363: Line 2,363:
Using functional binary search trees instead of hash tables:
Using functional binary search trees instead of hash tables:


<lang sml>structure StringMap = BinaryMapFn (struct
<syntaxhighlight lang="sml">structure StringMap = BinaryMapFn (struct
type ord_key = string
type ord_key = string
val compare = String.compare
val compare = String.compare
Line 2,372: Line 2,372:
and myMap = StringMap.empty;
and myMap = StringMap.empty;


val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));</lang>
val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));</syntaxhighlight>


{{works with|SML/NJ}}
{{works with|SML/NJ}}
Using hash tables:
Using hash tables:


<lang sml>exception NotFound;
<syntaxhighlight lang="sml">exception NotFound;


val keys = [ "foo", "bar", "baz" ]
val keys = [ "foo", "bar", "baz" ]
Line 2,383: Line 2,383:
and hash = HashTable.mkTable (HashString.hashString, op=) (42, NotFound);
and hash = HashTable.mkTable (HashString.hashString, op=) (42, NotFound);


ListPair.appEq (HashTable.insert hash) (keys, vals);</lang>
ListPair.appEq (HashTable.insert hash) (keys, vals);</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|1.2+}}
{{works with|Swift|1.2+}}
<lang swift>let keys = ["a","b","c"]
<syntaxhighlight lang="swift">let keys = ["a","b","c"]
let vals = [1,2,3]
let vals = [1,2,3]
var hash = [String: Int]()
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
for (key, val) in zip(keys, vals) {
hash[key] = val
hash[key] = val
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 2,401: Line 2,401:
"<i>lists</i> of equal length",
"<i>lists</i> of equal length",
then the task might look like this:
then the task might look like this:
<lang tcl>set keys [list fred bob joe]
<syntaxhighlight lang="tcl">set keys [list fred bob joe]
set values [list barber plumber tailor]
set values [list barber plumber tailor]
array set arr {}
array set arr {}
foreach a $keys b $values { set arr($a) $b }
foreach a $keys b $values { set arr($a) $b }


parray arr</lang>
parray arr</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,415: Line 2,415:


Alternatively, a dictionary could be used: <!-- http://ideone.com/6lI4k5 -->
Alternatively, a dictionary could be used: <!-- http://ideone.com/6lI4k5 -->
<lang tcl>package require Tcl 8.5
<syntaxhighlight lang="tcl">package require Tcl 8.5
set keys [list fred bob joe]
set keys [list fred bob joe]
Line 2,424: Line 2,424:
}
}
puts "jobs: [dict get $jobs]"</lang>
puts "jobs: [dict get $jobs]"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,434: Line 2,434:
===One-liner, using quasiquoted hash syntax===
===One-liner, using quasiquoted hash syntax===


<lang bash>$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))'
<syntaxhighlight lang="bash">$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))</lang>
#H(() (c 3) (b 2) (a 1))</syntaxhighlight>


===One-liner, using <code>hash-construct</code> function===
===One-liner, using <code>hash-construct</code> function===


<lang bash>$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))'
<syntaxhighlight lang="bash">$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))</lang>
#H(() (c 3) (b 2) (a 1))</syntaxhighlight>


===Explicit construction and stuffing===
===Explicit construction and stuffing===


<lang txrlisp>(defun hash-from-two (vec1 vec2 . hash-args)
<syntaxhighlight lang="txrlisp">(defun hash-from-two (vec1 vec2 . hash-args)
(let ((table (hash . hash-args)))
(let ((table (hash . hash-args)))
(mapcar (do sethash table) vec1 vec2)
(mapcar (do sethash table) vec1 vec2)
table))
table))


(prinl (hash-from-two #(a b c) #(1 2 3)))</lang>
(prinl (hash-from-two #(a b c) #(1 2 3)))</syntaxhighlight>


<pre>$ ./txr hash-from-two.tl
<pre>$ ./txr hash-from-two.tl
Line 2,456: Line 2,456:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bash|4}}
{{works with|Bash|4}}
<lang bash>keys=( foo bar baz )
<syntaxhighlight lang="bash">keys=( foo bar baz )
values=( 123 456 789 )
values=( 123 456 789 )
declare -A hash
declare -A hash
Line 2,466: Line 2,466:
for key in "${!hash[@]}"; do
for key in "${!hash[@]}"; do
printf "%s => %s\n" "$key" "${hash[$key]}"
printf "%s => %s\n" "$key" "${hash[$key]}"
done</lang>
done</syntaxhighlight>


{{out}}
{{out}}
Line 2,476: Line 2,476:
Using a sorted file as an associative array (see Creating an associative array for usage.)
Using a sorted file as an associative array (see Creating an associative array for usage.)


<lang bash>cat <<VAL >p.values
<syntaxhighlight lang="bash">cat <<VAL >p.values
apple
apple
boy
boy
Line 2,492: Line 2,492:
KEYS
KEYS


paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</lang>
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
There is a built-in operator for this.
There is a built-in operator for this.
<lang Ursala>keys = <'foo','bar','baz'>
<syntaxhighlight lang="ursala">keys = <'foo','bar','baz'>
values = <12354,145430,76748>
values = <12354,145430,76748>


hash_function = keys-$values</lang>
hash_function = keys-$values</syntaxhighlight>
test program:
test program:
<lang Ursala>#cast %nL
<syntaxhighlight lang="ursala">#cast %nL


test = hash_function* <'bar','baz','foo','bar'></lang>
test = hash_function* <'bar','baz','foo','bar'></syntaxhighlight>
{{out}}
{{out}}
<pre><145430,76748,12354,145430></pre>
<pre><145430,76748,12354,145430></pre>
Line 2,509: Line 2,509:
=={{header|Vala}}==
=={{header|Vala}}==
{{libheader|Gee}}
{{libheader|Gee}}
<lang vala>
<syntaxhighlight lang="vala">
using Gee;
using Gee;


Line 2,525: Line 2,525:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
Line 2,531: Line 2,531:
VBScript (and Visual Basic in general) calls hashes "dictionary objects".
VBScript (and Visual Basic in general) calls hashes "dictionary objects".


<lang vb>Set dict = CreateObject("Scripting.Dictionary")
<syntaxhighlight lang="vb">Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,539: Line 2,539:
MsgBox dict.Item("Linux")
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")</lang>
MsgBox dict.Item("Windows")</syntaxhighlight>


{{out}} (in message boxes):
{{out}} (in message boxes):
Line 2,561: Line 2,561:
and the order that the arguments are passed to the <code>Add</code> method.
and the order that the arguments are passed to the <code>Add</code> method.


<lang vb>Dim dict As New Collection
<syntaxhighlight lang="vb">Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,569: Line 2,569:
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")</lang>
Debug.Print dict.Item("Windows")</syntaxhighlight>


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang WDTE>let a => import 'arrays';
<syntaxhighlight lang="wdte">let a => import 'arrays';
let s => import 'stream';
let s => import 'stream';


Line 2,582: Line 2,582:
set scope k v;
set scope k v;
)
)
;</lang>
;</syntaxhighlight>


'''Example:'''
'''Example:'''


<lang WDTE>toScope
<syntaxhighlight lang="wdte">toScope
['a'; 'b'; 'c']
['a'; 'b'; 'c']
[1; 2; 3]
[1; 2; 3]
Line 2,595: Line 2,595:
-> s.collect
-> s.collect
-- io.writeln io.stdout
-- io.writeln io.stdout
;</lang>
;</syntaxhighlight>


{{out}}
{{out}}
Line 2,602: Line 2,602:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn main() {
<syntaxhighlight lang="vlang">fn main() {
keys := ["a", "b", "c"]
keys := ["a", "b", "c"]
vals := [1, 2, 3]
vals := [1, 2, 3]
Line 2,610: Line 2,610:
}
}
println(hash)
println(hash)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,618: Line 2,618:
=={{header|Wortel}}==
=={{header|Wortel}}==
Wortel has an inbuilt operator to do this: <code>@hash</code>.
Wortel has an inbuilt operator to do this: <code>@hash</code>.
<lang wortel>@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}</lang>
<syntaxhighlight lang="wortel">@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}</syntaxhighlight>
This function can also be defined as:
This function can also be defined as:
<lang wortel>^(@obj @zip)</lang>
<syntaxhighlight lang="wortel">^(@obj @zip)</syntaxhighlight>
Example:
Example:
<lang wortel>@let {
<syntaxhighlight lang="wortel">@let {
hash ^(@obj @zip)
hash ^(@obj @zip)
!!hash ["a" "b" "c"] [1 2 3]
!!hash ["a" "b" "c"] [1 2 3]
}</lang>
}</syntaxhighlight>
{{out|Returns}}
{{out|Returns}}
<pre>{a 1 b 2 c 3}</pre>
<pre>{a 1 b 2 c 3}</pre>
Line 2,631: Line 2,631:
=={{header|Wren}}==
=={{header|Wren}}==
Wren's built-in Map class does not guarantee (as here) that iteration order will be the same as the order in which elements were added.
Wren's built-in Map class does not guarantee (as here) that iteration order will be the same as the order in which elements were added.
<lang ecmascript>var keys = [1, 2, 3, 4, 5]
<syntaxhighlight lang="ecmascript">var keys = [1, 2, 3, 4, 5]
var values = ["first", "second", "third", "fourth","fifth"]
var values = ["first", "second", "third", "fourth","fifth"]
var hash = {}
var hash = {}
(0..4).each { |i| hash[keys[i]] = values[i] }
(0..4).each { |i| hash[keys[i]] = values[i] }
System.print(hash)</lang>
System.print(hash)</syntaxhighlight>


{{out}}
{{out}}
Line 2,643: Line 2,643:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
<syntaxhighlight lang="zkl">keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d:=keys.zip(vals).toDictionary();
d.println();
d.println();
d["b"].println();</lang>
d["b"].println();</syntaxhighlight>
{{out}}
{{out}}
<pre>D(a:1,b:2,c:3,d:4)
<pre>D(a:1,b:2,c:3,d:4)