Hash from two arrays: Difference between revisions

 
(16 intermediate revisions by 11 users not shown)
Line 19:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V keys = [‘a’, ‘b’, ‘c’]
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
print(hash_)</langsyntaxhighlight>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">package
{
public class MyClass
Line 39:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
<langsyntaxhighlight lang="ada">with Ada.Strings.Hash;
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
Line 85:
end loop;
end Hash_Map_Test;</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
Example:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#!/usr/bin/hopper
#include <hopper.h>
Line 192:
pause
exit(0)
</syntaxhighlight>
</lang>
Output:
<pre>Longitud HASH: 3
Line 329:
(Observation: some of these macros will be converted to libraries, due to their extension.)
 
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
/* macros HASH */
#defn createhash(_X_) _X__KEY={#VOID},_X__HASH={#VOID}
Line 382:
#define println {"\n"}print
 
</syntaxhighlight>
</lang>
 
=={{header|Argile}}==
{{works with|Argile|1.1.0}}
<langsyntaxhighlight Argilelang="argile">use std, array, hash
 
let keys = @["hexadecimal" "decimal" "octal" "binary"]
Line 393:
for each val int i from 0 to 3
hash[keys[i]] = values[i]
del hash hash</langsyntaxhighlight>
 
=={{header|Arturo}}==
<langsyntaxhighlight lang="rebol">h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h</langsyntaxhighlight>
{{out}}
Line 404:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">array1 := ["two", "three", "apple"]
array2 := [2, 3, "fruit"]
hash := {}
Loop % array1.maxIndex()
hash[array1[A_Index]] := array2[A_Index]
MsgBox % hash["apple"] "`n" hash["two"]</langsyntaxhighlight>
 
=={{header|AWK}}==
Awk arrays are used for both lists and hash maps.
<!-- http://ideone.com/MsdNUc -->
<langsyntaxhighlight lang="awk"># usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk
BEGIN {
if(!list1) list1="one two three"
Line 424:
for(i in c) print i,c[i]
}</langsyntaxhighlight>
 
{{out}}
Line 438:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
Line 457:
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> two three apple:?arr1
& 2 3 fruit:?arr2
& new$hash:?H
Line 470:
& (H..forall)$out
& ;
</syntaxhighlight>
</lang>
{{out}}
<pre>apple.fruit
Line 477:
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">zip = { keys, values |
h = [:]
keys.each_with_index { key, index |
Line 486:
}
 
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</langsyntaxhighlight>
 
=={{header|C}}==
Line 493:
following implementation tries to be somewhat generic to facilitate using alternative key and
value types.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 607:
}
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
===C# 1.0===
<langsyntaxhighlight lang="csharp">static class Program
{
static void Main()
Line 627:
}
}
}</langsyntaxhighlight>
 
<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:
<langsyntaxhighlight lang="csharp">h[keys[i]] = values[i];</langsyntaxhighlight>
 
===Modern===
Line 639:
<code>Enumerable.Zip</code> truncates the longer of its arguments.
 
<langsyntaxhighlight lang="csharp">using System.Linq;
 
static class Program
Line 652:
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <unordered_map>
#include <string>
 
Line 666:
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}</langsyntaxhighlight>
 
{{libheader|range-v3}}
<langsyntaxhighlight lang="cpp">#include <range/v3/view/zip.hpp>
#include <unordered_map>
#include <string>
Line 680:
std::unordered_map<std::string, std::string> hash(ranges::view::zip(keys, vals));
}
</syntaxhighlight>
</lang>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
value keys = [1, 2, 3];
value items = ['a', 'b', 'c'];
value hash = map(zipEntries(keys, items));
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(zipmap [\a \b \c] [1 2 3])</langsyntaxhighlight>
 
=={{header|Coco}}==
<langsyntaxhighlight lang="coco">keys = <[apple banana orange grape]>
values = <[red yellow orange purple]>
 
object = new
@[keys[i]] = values[i] for i til keys.length</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
keys = ['a','b','c']
values = [1,2,3]
map = {}
map[key] = values[i] for key, i in keys
</syntaxhighlight>
</lang>
 
=={{header|ColdFusion}}==
<langsyntaxhighlight ColdFusionlang="coldfusion"><cfscript>
function makeHash(keyArray, valueArray) {
var x = 1;
Line 721:
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
</cfscript></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
(assert (= (length vector-1) (length vector-2)))
(let ((table (make-hash-table :test test :size (length vector-1))))
(map nil (lambda (k v) (setf (gethash k table) v))
vector-1 vector-2)
table))</langsyntaxhighlight>
 
Or, using cl:loop:
 
<langsyntaxhighlight 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)))
with table = (make-hash-table :test test :size (length vector-1))
Line 740:
for v across vector-2
do (setf (gethash k table) v)
finally (return table)))</langsyntaxhighlight>
 
In Common Lisp terminology, a vector is a one-dimensional array.
Line 746:
=={{header|Crystal}}==
 
<langsyntaxhighlight lang="ruby">keys = ('a'..'z').to_a # => a, b, c ... z
vals = (1..26).to_a # => 1, 2, 3 ... 26
 
hash = Hash.zip(keys, vals)
p hash</langsyntaxhighlight>
 
<pre>
Line 757:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">void main() {
import std.array, std.range;
 
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :h_keys [ :one :two :three ]
local :h_values [ 1 2 3 ]
local :h {}
for item in h_keys:
set-to h item pop-from h_values
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Hash_from_two_arrays;
 
Line 817:
end.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 824:
c 3
</pre>
=={{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.
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_ary(keysDict)_values(a,b,c);
add_ary(valsDict)_values(1,2,3);
 
add_dict(aDict)_map([keysDict],[valsDict]);
 
add_hash(aHash)_hash[valsDict]; // Keys will be new uuids
 
reset_namespace[];</syntaxhighlight>
 
Arrays can manually be mapped from two arrays using a <code>_for</code> posit, for instance:
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me();
 
add_dict(bDict);
add_dict(cDict);
add_for(i)_from(0)_lessthan()_[keysDict]_length()_inc()
with_dict(bDict)_mapkeys()_[keysDict]_at[i]_mapvals()_[valsDict]_at[i];
[cDict]_map()_[keysDict]_at[i]_[valsDict]_at[i]; // alternative shortened syntax
;
 
reset_namespace[];</syntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def keys := ["one", "two", "three"]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'hash)
 
Line 842 ⟶ 867:
(hash-ref H 'elvis)
→ "the king"
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> keys = [:one, :two, :three]
[:one, :two, :three]
iex(2)> values = [1, 2, 3]
[1, 2, 3]
iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new)
%{one: 1, three: 3, two: 2}</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">
(let ((keys ["a" "b" "c"])
(values [1 2 3]))
(apply 'vector (cl-loop for i across keys for j across values collect (vector i j))))
</syntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
List keys = var["hal", 666, int[1,2,3]]
List vals = var["ibm", "devil", 123]
Map hash = keys.zip(vals)
writeLine(hash)
</syntaxhighlight>
{{out}}
<pre>
[hal:ibm,666:devil,[1,2,3]:123]
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).
</syntaxhighlight>
</lang>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: hashtables ;
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</langsyntaxhighlight>
 
=={{header|Falcon}}==
<langsyntaxhighlight lang="falcon">
keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]
</syntaxhighlight>
</lang>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 891 ⟶ 935:
}
}
</syntaxhighlight>
</lang>
 
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight 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 hash(Lbound(keys) To Ubound(keys))
Line 908 ⟶ 952:
Print keys(i); " "; hash(i)'; " "; i
Next i
Sleep</langsyntaxhighlight>
{{out}}
<pre> 1 one
Line 919 ⟶ 963:
=={{header|Frink}}==
There is a built-in dictionary/hash constructor that takes two arrays as input.
<langsyntaxhighlight lang="frink">
a = new dict[["a", "b", "c"], [1, 2, 3]]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
void local fn DoIt
CFArrayRef keys = @[@"Key1",@"Key2",@"Key3",@"Key4"]
CFArrayRef values = @[@"One",@"Two",@"Three",@"O'Leary"]
CFDictionaryRef dict = fn DictionaryWithObjectsForKeys( values, keys )
NSLog(@"%@",dict)
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
{
Key1 = One;
Key2 = Two;
Key3 = Three;
Key4 = "O'Leary";
}
</pre>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=944f0b9cbf60910e7ee7ea4191928a7c Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Line 939 ⟶ 1,009:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 951 ⟶ 1,021:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 963 ⟶ 1,033:
}
fmt.Println(hash)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 971 ⟶ 1,041:
=={{header|Groovy}}==
 
<langsyntaxhighlight lang="groovy">def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
}</langsyntaxhighlight>
 
Alternative Version:
<langsyntaxhighlight lang="groovy">List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']</langsyntaxhighlight>
 
=={{header|Harbour}}==
<langsyntaxhighlight lang="visualfoxpro">LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
LOCAL hash := { => }
LOCAL i, j
Line 991 ⟶ 1,061:
FOR EACH i, j IN arr1, arr2
hash[ i ] := j
NEXT</langsyntaxhighlight>
 
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
 
<langsyntaxhighlight lang="haskell">import Data.Map
 
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]</langsyntaxhighlight>
 
=={{header|Huginn}}==
<langsyntaxhighlight lang="huginn">from Algorithms import materialize, zip;
 
main() {
Line 1,008 ⟶ 1,078:
values = ['a', 'b', 'c'];
hash = materialize( zip( key, values ), lookup );
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">link ximage # to format the structure
 
procedure main(arglist) #: demonstrate hash from 2 lists
Line 1,022 ⟶ 1,092:
 
write(ximage(T)) # show result
end</langsyntaxhighlight>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke">{} addKeysAndValues([:a, :b, :c], [1, 2, 3])</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,033 ⟶ 1,103:
 
'''Solution:'''
<langsyntaxhighlight lang="j">hash=: vals {~ keys&i.</langsyntaxhighlight>
'''For example:'''
 
<langsyntaxhighlight lang="j"> keys=: 10?.100
vals=: > ;:'zero one two three four five six seven eight nine'
hash=: vals {~ keys&i.
Line 1,054 ⟶ 1,124:
six
seven
two</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="java">import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
Line 1,067 ⟶ 1,137:
hash.put(keys[i], vals[i]);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
===Iterative===
<langsyntaxhighlight lang="javascript">
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
Line 1,079 ⟶ 1,149:
map[ keys[i] ] = values[i];
}
</syntaxhighlight>
</lang>
 
===Iterative Using Foreach===
<langsyntaxhighlight lang="javascript">
function arrToObj(keys, vals) {
var map = {};
Line 1,090 ⟶ 1,160:
return map;
}
</syntaxhighlight>
</lang>
 
===Using Reduce===
<langsyntaxhighlight lang="javascript">
function arrToObj(keys, vals) {
return keys.reduce(function(map, key, index) {
Line 1,100 ⟶ 1,170:
}, {});
}
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
jq only supports hashing of strings. In the following, accordingly, we assume that
one array (keys) is an array of strings.
<langsyntaxhighlight lang="jq"># hash(keys) creates a JSON object with the given keys as keys
# and values taken from the input array in turn.
# "keys" must be an array of strings.
Line 1,116 ⟶ 1,186:
( {}; . + { (keys[$i]) : $values[$i] });
 
[1,2,3] | hash( ["a","b","c"] )</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="jq">jq -n -f Hash_from_two_arrays.jq
{
"a": 1,
"b": 2,
"c": 3
}</langsyntaxhighlight>
To hash an array of distinct integers, the tostring filter can be used, e.g.
[10,20,30] | hash( [1,2,3] | map(tostring) )
yields:<langsyntaxhighlight lang="jq">{
"1": 10,
"2": 20,
"3": 30
}</langsyntaxhighlight>
 
=={{header|Jsish}}==
From Javascript.
<langsyntaxhighlight lang="javascript">/* Hash from two arrays, in Jsish */
function hashTwo(k:array, v:array):object {
var hash = {};
Line 1,153 ⟶ 1,223:
hashTwo([], []) ==> {}
=!EXPECTEND!=
*/</langsyntaxhighlight>
{{out}}
<pre>prompt$ jsish -u hashTwo.jsi
Line 1,163 ⟶ 1,233:
 
'''Using comprehension''':
<langsyntaxhighlight lang="julia">k = ["a", "b", "c"]
v = [1, 2, 3]
 
Dict(ki => vi for (ki, vi) in zip(k, v))</langsyntaxhighlight>
 
'''Using constructor''':
<syntaxhighlight lang ="julia">Dict(zip(keys, values))</langsyntaxhighlight>
 
'''Specifying types''':
<langsyntaxhighlight lang="julia">Dict{String,Int32}(zip(keys, values))</langsyntaxhighlight>
 
=={{header|K}}==
The keys in a dictionary must be a symbol.
<langsyntaxhighlight Klang="k"> a: `zero `one `two / symbols
b: 0 1 2
 
Line 1,185 ⟶ 1,255:
 
d[`one]
1</langsyntaxhighlight>
 
Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols).
 
<langsyntaxhighlight Klang="k"> keys: !10 / 0..9
split:{1_'(&x=y)_ x:y,x}
vals:split["zero one two three four five six seven eight nine";" "]
Line 1,207 ⟶ 1,277:
 
$d[s 1] / leading "$" converts back to string
"one"</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun main(args: Array<String>) {
Line 1,217 ⟶ 1,287:
val hash = mapOf(*names.zip(ages).toTypedArray())
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}</langsyntaxhighlight>
 
{{out}}
Line 1,228 ⟶ 1,298:
 
=={{header|Lang5}}==
<langsyntaxhighlight lang="lang5">: >table 2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table</langsyntaxhighlight>
 
=={{header|langur}}==
=== the easy way ===
<langsyntaxhighlight lang="langur">writeln(hash toHash wfw/a b c d/, [1, 2, 3, 4]</lang>)
</syntaxhighlight>
 
Note that wfw/a b c d/ is a semantic convenience equivalent to ["a", "b", "c", "d"].
 
=== a longer way ===
Using the append operator would silently overwrite hash values for matching keys, but the more() function will not.
<langsyntaxhighlight lang="langur">val .new = foldfrom(
ffn(.hash, .key, .value) more .hash, h{.key: .value},
h{}hash(), wfw/a b c d/, [1, 2, 3, 4],
)
 
writeln .new</langsyntaxhighlight>
 
{{out}}
<pre>h{"d": 4, "a": 1, "b": 2, "c": 3}</pre>
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">local(
array1 = array('a', 'b', 'c'),
array2 = array(1, 2, 3),
Line 1,260 ⟶ 1,331:
}
 
#hash</langsyntaxhighlight>
-> map(a = 1, b = 2, c = 3)
 
=={{header|LFE}}==
<langsyntaxhighlight lang="lisp">(let* ((keys (list 'foo 'bar 'baz))
(vals (list '"foo data" '"bar data" '"baz data"))
(tuples (: lists zipwith
Line 1,270 ⟶ 1,341:
(my-dict (: dict from_list tuples)))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">keys = ["a","b","c"]
values = [1,2,3]
 
Line 1,283 ⟶ 1,354:
 
put props
-- ["a": 1, "b": 2, "c": 3]</langsyntaxhighlight>
 
=={{header|LiveCode}}==
<langsyntaxhighlight LiveCodelang="livecode">put "a,b,c" into list1
put 10,20,30 into list2
split list1 using comma
Line 1,297 ⟶ 1,368:
 
-- ouput
-- a:10,b:20,c:30</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function(keys,values)
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckAll {
Module CheckVectorType {
Line 1,334 ⟶ 1,405:
}
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
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function MakeHash(&a$(), &b$()) {
Line 1,381 ⟶ 1,452:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">A := [1, 2, 3];
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
 
Line 1,395 ⟶ 1,466:
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
See [[Associative arrays/Creation#MATLAB_.2F_Octave|Associative arrays/Creation]] for clarification of limitations and differences between the two methods.
===MATLAB/Octave: structs===
<langsyntaxhighlight MATLABlang="matlab">function s = StructFromArrays(allKeys, allVals)
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
Line 1,414 ⟶ 1,485:
end
end
end</langsyntaxhighlight>
{{out}}
<pre>>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27])
Line 1,440 ⟶ 1,511:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]
 
Line 1,448 ⟶ 1,519:
end for
 
print d</langsyntaxhighlight>
{{out}}
<pre>{"bar": "miss", "foo": "little", "val": "muffet"}</pre>
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
Line 1,472 ⟶ 1,543:
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)</langsyntaxhighlight>
 
{{out}}
Line 1,484 ⟶ 1,555:
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Collections;
Line 1,499 ⟶ 1,570:
WriteLine("{0}: {1}", item.Key, item.Value);
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
=== REXX Style ===
{{trans|REXX}}
<langsyntaxhighlight lang="netrexx">/* NetRexx program ****************************************************
* 04.11.2012 Walter Pachl derived from REXX
**********************************************************************/
Line 1,525 ⟶ 1,596:
Say ' 'keys
Parse Ask z
Say z '->' value[z]</langsyntaxhighlight>
 
=== Java Collections ===
NetRexx has access to Java's Collection objects too.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 1,570 ⟶ 1,641:
 
return
</syntaxhighlight>
</lang>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import tables, sequtils
 
let keys = @['a','b','c']
let values = @[1, 2, 3]
 
let table = toTable zip(keys, values)</langsyntaxhighlight>
 
=={{header|Oberon-2}}==
Works with oo2c version 2
<langsyntaxhighlight lang="oberon2">
MODULE HashFromArrays;
IMPORT
Line 1,618 ⟶ 1,689:
Do;
END HashFromArrays.
</syntaxhighlight>
</lang>
 
=={{header|Objeck}}==
 
<langsyntaxhighlight lang="objeck">
use Structure;
 
Line 1,637 ⟶ 1,708:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</langsyntaxhighlight>
 
=={{header|OCaml}}==
The idiomatic solution uses lists rather than arrays.
 
<langsyntaxhighlight lang="ocaml">let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;
 
List.iter2 (Hashtbl.add hash) keys vals;;</langsyntaxhighlight>
 
The solution is similar with arrays.
 
<langsyntaxhighlight lang="ocaml">let keys = [| "foo"; "bar"; "baz" |]
and vals = [| 16384; 32768; 65536 |]
and hash = Hashtbl.create 0;;
 
Array.iter2 (Hashtbl.add hash) keys vals;;</langsyntaxhighlight>
 
In either case, an exception is raised if the inputs are different lengths.
Line 1,666 ⟶ 1,737:
If you want to use functional binary search trees instead of hash tables:
 
<langsyntaxhighlight lang="ocaml">module StringMap = Map.Make (String);;
 
let keys = [ "foo"; "bar"; "baz" ]
Line 1,672 ⟶ 1,743:
and map = StringMap.empty;;
 
let map = List.fold_right2 StringMap.add keys vals map;;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight ooRexxlang="oorexx">array1 = .array~of("Rick", "Mike", "David")
array2 = .array~of("555-9862", "555-5309", "555-6666")
 
Line 1,687 ⟶ 1,758:
Say 'Enter a name'
Parse Pull name
Say name '->' hash[name]</langsyntaxhighlight>
{{out}}
<pre>Enter a name
Line 1,694 ⟶ 1,765:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {ZipRecord Keys Values}
{List.toRecord unit {List.zip Keys Values MakePair}}
Line 1,703 ⟶ 1,774:
end
in
{Show {ZipRecord [a b c] [1 2 3]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{libheader|contnrs}}
<langsyntaxhighlight lang="pascal">program HashFromTwoArrays (Output);
 
uses
Line 1,729 ⟶ 1,800:
writeln ('Length of hash table: ', hash.Count);
hash.Destroy;
end.</langsyntaxhighlight>
{{out}}
<pre>% ./HashFromTwoArrays
Line 1,736 ⟶ 1,807:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;</langsyntaxhighlight>
 
Alternatively, using {{libheader|List::MoreUtils}}:
 
<langsyntaxhighlight lang="perl">use List::MoreUtils qw(zip);
my %hash = zip @keys, @vals;</langsyntaxhighlight>
 
=={{header|Phix}}==
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 1,766 ⟶ 1,837:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,775 ⟶ 1,846:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def getd /# array key -- array data #/
Line 1,791 ⟶ 1,862:
"two" getd print nl
PI getd tostr print nl
3 getd print</langsyntaxhighlight>
{{out}}
<pre>
Line 1,802 ⟶ 1,873:
=={{header|PHP}}==
{{works with|PHP|5}}
<langsyntaxhighlight lang="php">$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);</langsyntaxhighlight>
 
{{works with|PHP|4}}
<langsyntaxhighlight lang="php">$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
A = [a,b,c,d,e],
B = [1,2,3,4,5],
Map = new_map([K=V : {K,V} in zip(A,B)]),
println(Map).</langsyntaxhighlight>
 
{{out}}
Line 1,826 ⟶ 1,897:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let (Keys '(one two three) Values (1 2 3))
(mapc println
(mapcar cons Keys Values) ) )</langsyntaxhighlight>
{{out}}
<pre>(one . 1)
Line 1,836 ⟶ 1,907:
=={{header|Pike}}==
Any data type can be used as indices (keys) and values.
<syntaxhighlight lang="pike">
<lang Pike>
array indices = ({ "a", "b", 42 });
array values = ({ Image.Color(0,0,0), "hello", "world" });
mapping m = mkmapping( indices, values );
write("%O\n", m);
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,853 ⟶ 1,924:
=={{header|Pop11}}==
 
<langsyntaxhighlight lang="pop11">vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars i;
Line 1,861 ⟶ 1,932:
for i from 1 to length(keys) do
vals(i) -> ht(keys(i));
endfor;</langsyntaxhighlight>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
% push our arrays
[/a /b /c /d /e] [1 2 3 4 5]
Line 1,872 ⟶ 1,943:
% show that we have created the hash
{= =} forall
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function create_hash ([array] $keys, [array] $values) {
$h = @{}
if ($keys.Length -ne $values.Length) {
Line 1,887 ⟶ 1,958:
}
return $h
}</langsyntaxhighlight>
 
=={{header|Prolog}}==
 
<langsyntaxhighlight lang="prolog">% this one with side effect hash table creation
 
:-dynamic hash/2.
Line 1,909 ⟶ 1,980:
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).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Dim keys.s(3)
Dim vals.s(3)
NewMap Hash.s()
Line 1,923 ⟶ 1,994:
ForEach Hash()
Debug Hash()
Next</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3.0+ and 2.7}}
Shows off the dict comprehensions in Python 3 (that were back-ported to 2.7):
<langsyntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}</langsyntaxhighlight>
 
{{works with|Python|2.2+}}
<langsyntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(zip(keys, values))
Line 1,939 ⟶ 2,010:
# Lazily, Python 2.3+, not 3.x:
from itertools import izip
hash = dict(izip(keys, values))</langsyntaxhighlight>
 
{{works with|Python|2.0+}}
<langsyntaxhighlight lang="python">keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {}
for k,v in zip(keys, values):
hash[k] = v</langsyntaxhighlight>
 
The original (Ruby) example uses a range of different types as keys. Here is similar in python (run at the shell):
<langsyntaxhighlight lang="python">>>> class Hashable(object):
def __hash__(self):
return id(self) ^ 0xBEEF
Line 1,989 ⟶ 2,060:
<__main__.Hashable object at 0x012AFC50> : 0
>>> # 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</langsyntaxhighlight>
 
=={{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]].
<langsyntaxhighlight lang="r"># Set up hash table
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
Line 2,000 ⟶ 2,071:
values["Sam Doe"] # vals["Sam Doe"]
# Get all keys corresponding to a value
names(values)[values==152] # "John Smith" "Sandra Dee"</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
(make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))</langsyntaxhighlight>
 
Alternatively:
<langsyntaxhighlight lang="racket">
(define (connect keys vals) (for/hash ([k keys] [v vals]) (values k v)))
;; Example:
(connect #("a" "b" "c" "d") #(1 2 3 4))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,019 ⟶ 2,090:
 
{{works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>my @keys = <a b c d e>;
my @values = ^5;
 
Line 2,037 ⟶ 2,108:
 
quietly # suppress warnings about unused hash
{ @keys »=>« @values }; # Will fail if the lists differ in length</langsyntaxhighlight>
 
=={{header|Raven}}==
 
<langsyntaxhighlight lang="raven">[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals
$keys $vals combine as $hash</langsyntaxhighlight>
 
=={{header|REXX}}==
This REXX version allows multiple keys for a value, &nbsp; the keys are case sensitive.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates hashing of a stemmed array (from a key or multiple keys)*/
key.= /*names of the nine regular polygons. */
vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon'
Line 2,068 ⟶ 2,139:
hash.map= word(@val, j)
end /*j*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input value of: &nbsp; &nbsp; <tt> phive </tt>}}
<pre>
Line 2,079 ⟶ 2,150:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Hash from two arrays
 
Line 2,094 ⟶ 2,165:
see c[i] + " " + i + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,100 ⟶ 2,171:
two 2
three 3
</pre>
 
=={{header|RPL}}==
≪ <span style="color:red">2</span> →LIST ≫ '<span style="color:blue">→HASH</span>' STO
≪ OVER <span style="color:red">1</span> GET SWAP POS
SWAP <span style="color:red">2</span> GET
SWAP GET
≫ '<span style="color:blue">HASH→</span>' STO
 
<span style="color:red">{ "one" "two" "three" } { 1 2 3 }</span> <span style="color:blue">→HASH</span>
DUP '<span style="color:green">MYHASH</span>' STO
<span style="color:green">MYHASH</span> <span style="color:red">2</span> <span style="color:blue">HASH→</span>
{{out}}
<pre>
2: { { 1 2 3 } { "one" "two" "three" } }
1: "two"
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]
Line 2,113 ⟶ 2,201:
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123
</syntaxhighlight>
</lang>
 
In Ruby 2.1 the method "to_h" was introduced:
<langsyntaxhighlight lang="ruby">keys = ['hal', 666, [1,2,3]]
vals = ['ibm', 'devil', 123]
 
keys.zip(vals).to_h</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
 
fn main() {
Line 2,130 ⟶ 2,218:
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
}</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class ZIPPER{K,E} is
zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
pre k.size = e.size
Line 2,155 ⟶ 2,243:
end;
 
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val keys = List(1, 2, 3)
val values = Array("A", "B", "C") // Array mixed with List
val map = keys.zip(values).toMap // and other Seq are possible.
Line 2,164 ⟶ 2,252:
// Testing
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
println("Successfully completed without errors.")</langsyntaxhighlight>
 
=={{header|Scheme}}==
=== Using [http://srfi.schemers.org/srfi-69/srfi-69.html SRFI 69] ===
<langsyntaxhighlight lang="scheme">(define (lists->hash-table keys values . rest)
(apply alist->hash-table (map cons keys values) rest))</langsyntaxhighlight>
 
=== Using association lists ===
<langsyntaxhighlight lang="scheme">;; Using SRFI-1, R6RS, or R7RS association lists.
 
;; Because the task calls for ‘arrays’, I start with actual arrays
Line 2,194 ⟶ 2,282:
;; ("b" . 2)
;; ("d" . 4)
;;</langsyntaxhighlight>
 
=== Using [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] ===
Line 2,200 ⟶ 2,288:
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.
 
<langsyntaxhighlight lang="scheme">(import (associative-arrays))
 
;; Because the task calls for ‘arrays’, I start with actual arrays
Line 2,230 ⟶ 2,318:
;;
;; Looking up "b" and "d": 2 4
;;</langsyntaxhighlight>
 
Side note: association lists can be used in either a persistent or non-persistent manner.
Line 2,236 ⟶ 2,324:
=={{header|Seed7}}==
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const type: numericHash is hash [string] integer;
Line 2,250 ⟶ 2,338:
myHash @:= [keyList[number]] valueList[number];
end for;
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">
set keyList to ["red", "green", "blue"]
set valueList to [150,0,128]
Line 2,264 ⟶ 2,352:
--> (blue:"128", green:"0", red:"150")
 
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var keys = %w(a b c)
var vals = [1, 2, 3]
 
var hash = Hash()
hash{keys...} = vals...
say hash</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Array extend [
dictionaryWithValues: array [ |d|
d := Dictionary new.
Line 2,289 ⟶ 2,377:
 
({ 'red' . 'one' . 'two' }
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</langsyntaxhighlight>
 
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Dictionary
withKeys:#('one' 'two' 'three')
andValues:#('eins' 'zwei' 'drei')</langsyntaxhighlight>
 
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">Dictionary withAssociations:{ 'one'->1 . 'two'->2 . 'three'->3 }</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 2,306 ⟶ 2,394:
{{works with|CSnobol}}
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* # Fill arrays
keys = array(5); vals = array(5)
ks = 'ABCDE'; vs = '12345'
Line 2,321 ⟶ 2,409:
str = str ch ':' hash<ch> ' ' :(tloop)
out output = str
end</langsyntaxhighlight>
 
{{out}}
Line 2,327 ⟶ 2,415:
 
=={{header|Sparkling}}==
<langsyntaxhighlight lang="sparkling">let keys = { "foo", "bar", "baz" };
let vals = { 13, 37, 42 };
var hash = {};
for var i = 0; i < sizeof keys; i++ {
hash[keys[i]] = vals[i];
}</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Line 2,338 ⟶ 2,426:
Using functional binary search trees instead of hash tables:
 
<langsyntaxhighlight lang="sml">structure StringMap = BinaryMapFn (struct
type ord_key = string
val compare = String.compare
Line 2,347 ⟶ 2,435:
and myMap = StringMap.empty;
 
val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));</langsyntaxhighlight>
 
{{works with|SML/NJ}}
Using hash tables:
 
<langsyntaxhighlight lang="sml">exception NotFound;
 
val keys = [ "foo", "bar", "baz" ]
Line 2,358 ⟶ 2,446:
and hash = HashTable.mkTable (HashString.hashString, op=) (42, NotFound);
 
ListPair.appEq (HashTable.insert hash) (keys, vals);</langsyntaxhighlight>
 
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<langsyntaxhighlight lang="swift">let keys = ["a","b","c"]
let vals = [1,2,3]
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
hash[key] = val
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,376 ⟶ 2,464:
"<i>lists</i> of equal length",
then the task might look like this:
<langsyntaxhighlight lang="tcl">set keys [list fred bob joe]
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set arr($a) $b }
 
parray arr</langsyntaxhighlight>
{{out}}
<pre>
Line 2,390 ⟶ 2,478:
 
Alternatively, a dictionary could be used: <!-- http://ideone.com/6lI4k5 -->
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
set keys [list fred bob joe]
Line 2,399 ⟶ 2,487:
}
puts "jobs: [dict get $jobs]"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,409 ⟶ 2,497:
===One-liner, using quasiquoted hash syntax===
 
<langsyntaxhighlight lang="bash">$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))</langsyntaxhighlight>
 
===One-liner, using <code>hash-construct</code> function===
 
<langsyntaxhighlight lang="bash">$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))</langsyntaxhighlight>
 
===Explicit construction and stuffing===
 
<langsyntaxhighlight lang="txrlisp">(defun hash-from-two (vec1 vec2 . hash-args)
(let ((table (hash . hash-args)))
(mapcar (do sethash table) vec1 vec2)
table))
 
(prinl (hash-from-two #(a b c) #(1 2 3)))</langsyntaxhighlight>
 
<pre>$ ./txr hash-from-two.tl
Line 2,431 ⟶ 2,519:
=={{header|UNIX Shell}}==
{{works with|Bash|4}}
<langsyntaxhighlight lang="bash">keys=( foo bar baz )
values=( 123 456 789 )
declare -A hash
Line 2,441 ⟶ 2,529:
for key in "${!hash[@]}"; do
printf "%s => %s\n" "$key" "${hash[$key]}"
done</langsyntaxhighlight>
 
{{out}}
Line 2,451 ⟶ 2,539:
Using a sorted file as an associative array (see Creating an associative array for usage.)
 
<langsyntaxhighlight lang="bash">cat <<VAL >p.values
apple
boy
Line 2,467 ⟶ 2,555:
KEYS
 
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</langsyntaxhighlight>
 
=={{header|Ursala}}==
There is a built-in operator for this.
<langsyntaxhighlight Ursalalang="ursala">keys = <'foo','bar','baz'>
values = <12354,145430,76748>
 
hash_function = keys-$values</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %nL
 
test = hash_function* <'bar','baz','foo','bar'></langsyntaxhighlight>
{{out}}
<pre><145430,76748,12354,145430></pre>
Line 2,484 ⟶ 2,572:
=={{header|Vala}}==
{{libheader|Gee}}
<langsyntaxhighlight lang="vala">
using Gee;
 
Line 2,500 ⟶ 2,588:
}
}
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
Line 2,506 ⟶ 2,594:
VBScript (and Visual Basic in general) calls hashes "dictionary objects".
 
<langsyntaxhighlight lang="vb">Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,514 ⟶ 2,602:
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")</langsyntaxhighlight>
 
{{out}} (in message boxes):
Line 2,536 ⟶ 2,624:
and the order that the arguments are passed to the <code>Add</code> method.
 
<langsyntaxhighlight lang="vb">Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,544 ⟶ 2,632:
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")</langsyntaxhighlight>
 
=={{header|WDTE}}==
<langsyntaxhighlight WDTElang="wdte">let a => import 'arrays';
let s => import 'stream';
 
Line 2,557 ⟶ 2,645:
set scope k v;
)
;</langsyntaxhighlight>
 
'''Example:'''
 
<langsyntaxhighlight WDTElang="wdte">toScope
['a'; 'b'; 'c']
[1; 2; 3]
Line 2,570 ⟶ 2,658:
-> s.collect
-- io.writeln io.stdout
;</langsyntaxhighlight>
 
{{out}}
Line 2,576 ⟶ 2,664:
<pre>[[a; 1]; [b; 2]; [c; 3]]</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
keys := ["a", "b", "c"]
vals := [1, 2, 3]
Line 2,585 ⟶ 2,673:
}
println(hash)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,593 ⟶ 2,681:
=={{header|Wortel}}==
Wortel has an inbuilt operator to do this: <code>@hash</code>.
<langsyntaxhighlight lang="wortel">@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}</langsyntaxhighlight>
This function can also be defined as:
<syntaxhighlight lang ="wortel">^(@obj @zip)</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="wortel">@let {
hash ^(@obj @zip)
!!hash ["a" "b" "c"] [1 2 3]
}</langsyntaxhighlight>
{{out|Returns}}
<pre>{a 1 b 2 c 3}</pre>
Line 2,606 ⟶ 2,694:
=={{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.
<langsyntaxhighlight ecmascriptlang="wren">var keys = [1, 2, 3, 4, 5]
var values = ["first", "second", "third", "fourth","fifth"]
var hash = {}
(0..4).each { |i| hash[keys[i]] = values[i] }
System.print(hash)</langsyntaxhighlight>
 
{{out}}
Line 2,616 ⟶ 2,704:
{2: second, 1: first, 3: third, 5: fifth, 4: fourth}
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">func Code(Str); \Return a simple, perfect hash code for the Keys used here
char Str;
return Str(2) & 7;
 
int Keys, Values, I, Hash(8);
[Keys:= ["first", "second", "third", "fourth", "fifth", "sixth"];
Values:= [1, 2, 3, 4, 5, 6];
for I:= 0 to 6-1 do
Hash(Code(Keys(I))):= Values(I);
IntOut(0, Hash(Code("second"))); CrLf(0);
IntOut(0, Hash(Code("sixth"))); CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
2
6
</pre>
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">data "1", "one", "2", "two", "3", "three", "4", "four", "5", "five"
 
dim keys$(5), values$(5)
dim hash$(5)
 
for i = 1 to arraysize(keys$(), 1)
read a$, b$
keys$(i) = a$
values$(i) = b$
next i
 
for i = 1 to arraysize(values$(), 1)
temp = val(keys$(i))
hash$(temp) = values$(i)
next i
 
for i = 1 to arraysize(hash$(), 1)
print keys$(i), " ", hash$(i)
next i
end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println();</langsyntaxhighlight>
{{out}}
<pre>D(a:1,b:2,c:3,d:4)
885

edits