Hash from two arrays: Difference between revisions
→{{header|langur}}
(Added Pike implementation) |
Langurmonkey (talk | contribs) |
||
(38 intermediate revisions by 21 users not shown) | |||
Line 19:
{{trans|Python}}
<
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
print(hash_)</
=={{header|ActionScript}}==
<
{
public class MyClass
Line 39:
}
}
}</
=={{header|Ada}}==
{{works with|GNAT|GPL 2007}}
<
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
Line 85:
end loop;
end Hash_Map_Test;</
=={{header|Amazing Hopper}}==
Example:
<syntaxhighlight lang="amazing hopper">
#!/usr/bin/hopper
#include <hopper.h>
main:
new hash(h)
add hash(h,"chile" :: 100)
add hash(h,"argentina"::200)
add hash(h,"brasil"::300)
{"\nLongitud HASH: "},len hash(h),println
println(hash(h))
println( get value("argentina",h) )
println( get value("chile",h) )
try
println( get value("guyana",h) )
catch(e)
{"***[",e,"]: "}get str error,println
finish
println( get key(300,h) )
println( get key(100,h) )
mod value("chile",101,h)
mod key(200,"madagascar",h)
try
mod key(130,"londres",h)
println( get key(130,h) )
catch(e)
{"***[",e,"]: "}get str error,println
finish
println( get key(200,h) )
println( get value("chile",h) )
println("HASH actual: \n")
println(hash(h))
{"\nLongitud HASH: "},len hash(h),println
put after value (200,"colombia",400,h)
put value (200,"mexico",401,h)
println(hash(h))
put after key ("chile","antartida",110,h)
put key ("chile","peru",99,h)
println("HASH actual: \n")
println(hash(h))
{"\nLongitud HASH: "},len hash(h),println
del by key("brasil",h)
del by value(101,h)
{"\nLongitud HASH: "},len hash(h),println
println(hash(h))
sort hash(h)
{"\nORDENADO: \n"}println
println(hash(h))
y={} // para un stack de arreglos.
x=0,{5,5}rand array(x)
{x}push(y)
add hash(h,"arreglo 1"::x)
{"Ojalá que llueva café en el campo"}strtoutf8,push(y)
clear(x),w=0,{6,2}rand array(w)
{w}push(y)
add hash(h,"arreglo 2"::w)
clear(w)
add hash(h,"objeto",y)
println(hash(h))
println("arreglo 2?\n")
get value("arreglo 2",h)
println
println("arreglo 1?\n")
get value("arreglo 1",h)
println
/* NO PUEDES ORDENAR UN HASH QUE CONTENGA ARRAYS
PORQUE SE BLOQUEARA EL PROGRAMA:
sort hash(h)
{"\nORDENADO: \n"}println
println(hash(h)) */
println("Objeto?\n")
get value("objeto",h)
z=0,mov(z)
/* Esto fallará, porque no se puede hacer un
push de pushs*/
pop(z),println
pop(z),println
pop(z),println
{"Esto significa que no puedes meter un stack dentro de un hash\nsolo arrays de cualquier dimension"}println
/* esto está bien, porque es un stack simple
aunque contenga arreglos como elementos. */
pop(y),println
{"Dato en la última posición del stack:"}strtoutf8,{"\n"},[1:end,1:end]get(y),println
{"Esto significa que, si vas a meter arreglos dentro de un stack\nsácalos con POP antes de usarlo"}strtoutf8,println
pop(y),println
pop(y),println
pause
exit(0)
</syntaxhighlight>
Output:
<pre>Longitud HASH: 3
chile 100
argentina 200
brasil 300
200
100
***[2000]: getvalue: key not found
brasil
chile
***[2003]: modkey: value not found
madagascar
101
HASH actual:
chile 101
madagascar 200
brasil 300
Longitud HASH: 3
chile 101
mexico 401
madagascar 200
colombia 400
brasil 300
HASH actual:
peru 99
chile 101
antartida 110
mexico 401
madagascar 200
colombia 400
brasil 300
Longitud HASH: 7
Longitud HASH: 5
peru 99
antartida 110
mexico 401
madagascar 200
colombia 400
ORDENADO:
antartida 110
colombia 400
madagascar 200
mexico 401
peru 99
antartida 110
colombia 400
madagascar 200
mexico 401
peru 99
arreglo 1
arreglo 2
objeto
arreglo 2?
0.333623 0.056282
0.043443 0.218781
0.535042 0.147832
0.0998848 0.852316
0.89247 0.806435
0.148637 0.215199
arreglo 1?
0.881104 0.317274 0.744638 0.70655 0.296321
0.322729 0.49368 0.00842611 0.302231 0.74979
0.541794 0.139073 0.503212 0.586376 0.81519
0.282293 0.47536 0.822661 0.861344 0.427054
0.671334 0.0660376 0.441688 0.742367 0.50555
Objeto?
0.744638 0.70655 0.296321
0.00842611 0.302231 0.74979
0.503212 0.586376 0.81519
0.822661 0.861344 0.427054
0.441688 0.742367 0.50555
Esto significa que no puedes meter un stack dentro de un hash
solo arrays de cualquier dimension
0.333623 0.056282
0.043443 0.218781
0.535042 0.147832
0.0998848 0.852316
0.89247 0.806435
0.148637 0.215199
Dato en la última posición del stack:
0.881104 0.322729 0.541794 0.282293 0.671334
0.317274 0.49368 0.139073 0.47536 0.0660376
0.744638 0.00842611 0.503212 0.822661 0.441688
0.70655 0.302231 0.586376 0.861344 0.742367
0.296321 0.74979 0.81519 0.427054 0.50555
Esto significa que, si vas a meter arreglos dentro de un stack
sácalos con POP antes de usarlo
Ojalá que llueva café en el campo
0.881104 0.317274 0.744638 0.70655 0.296321
0.322729 0.49368 0.00842611 0.302231 0.74979
0.541794 0.139073 0.503212 0.586376 0.81519
0.282293 0.47536 0.822661 0.861344 0.427054
0.671334 0.0660376 0.441688 0.742367 0.50555
</pre>
Macros used in the example, located in "hopper.h".
(Observation: some of these macros will be converted to libraries, due to their extension.)
<syntaxhighlight lang="amazing hopper">
/* macros HASH */
#defn createhash(_X_) _X__KEY={#VOID},_X__HASH={#VOID}
#synon createhash newhash
#defn addhash(_X_,_K_,_H_) {_H_}push(_X__HASH),{_K_}push(_X__KEY)
#defn getvalue(_X_,_Y_) _Y_03Rx0W91=0,{_X_,_Y__KEY},array(1),dup,zero?do{{"getvalue: key not found"}throw(2000)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]get(_Y__HASH),clearmark,
#defn getkey(_X_,_Y_) _Y_03Rx0W91=0,{_X_,_Y__HASH},array(1),dup,zero?do{{"getkey: value not found"}throw(2001)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]get(_Y__KEY),clearmark,
#defn modvalue(_K_,_H_,_X_) _Y_03Rx0W91=0,{_K_,_X__KEY},array(1),dup,zero?do{{"modvalue: key not found"}throw(2002)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]{_H_}put(_X__HASH),clearmark,
#defn modkey(_H_,_K_,_X_) _Y_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"modkey: value not found"}throw(2003)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]{_K_}put(_X__KEY),clearmark,
#defn putaftervalue(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"putaftervalue: value not found"}throw(2006)}\
plus(1),mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3)
#defn putvalue(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"putvalue: value not found"}throw(2006)}\
mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn putafterkey(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__KEY},array(1),dup,zero?do{{"putafterkey: key not found"}throw(2007)}\
plus(1),mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn putkey(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__KEY},array(1),dup,zero?do{{"putkey: value not found"}throw(2008)}\
mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn delbyvalue(_H_,_X_) {_H_,_X__HASH},array(1),dup,zero?do{{"delbyvalue: value not found"}throw(2004)},\
{_X__KEY},keep,array(4),{_X__HASH},array(4),clearstack
#defn delbykey(_K_,_X_) {_K_,_X__KEY},array(1),dup,zero?do{{"delbykey: key not found"}throw(2005)},\
{_X__KEY},keep,array(4),{_X__HASH},array(4),clearstack
#defn sorthash(_X_) #RAND,_LEN_#RNDV=0,_DUP_H#RNDV=_X__HASH,_DUP_K#RNDV=_X__KEY,\
{_X__KEY}keep,length,mov(_LEN_#RNDV),array(0),\
_POS_#RNDV=0,_HASH_LOOP_#RNDV:,[_LEN_#RNDV]get(_X__KEY),{_DUP_K#RNDV}array(1),\
mov(_POS_#RNDV),[_POS_#RNDV]get(_DUP_H#RNDV),[_LEN_#RNDV]put(_X__HASH),\
--_LEN_#RNDV,{_LEN_#RNDV},jnz(_HASH_LOOP_#RNDV),clear(_DUP_H#RNDV),clear(_DUP_K#RNDV)
#defn lenhash(_X_) {_X__HASH}length,
#defn hash(_X_) #RAND,_TMP_#RNDV=0,{_X__HASH,_X__KEY}catcol(_TMP_#RNDV),{_TMP_#RNDV},clear(_TMP_#RNDV),
/* Other... */
/* TRY/CATCH */
#defn try swtrap( #CATCH ),
#defn raise(_ERR_,_M_) {_M_}, throw(_ERR_),
#defn catch(_X_) jmp(#ENDCATCH), %CATCH:, clearstack,_X_=0, gettry(_X_), // gettry hace poptry internamente?
#defn finish %ENDCATCH:, popcatch
/* print... */
#defn println(_X_) #ATOM #CMPLX,{"\n"} print
#define println {"\n"}print
</syntaxhighlight>
=={{header|Argile}}==
{{works with|Argile|1.1.0}}
<
let keys = @["hexadecimal" "decimal" "octal" "binary"]
Line 96 ⟶ 393:
for each val int i from 0 to 3
hash[keys[i]] = values[i]
del hash hash</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h</syntaxhighlight>
{{out}}
<pre>
=={{header|AutoHotkey}}==
<
array2 := [2, 3, "fruit"]
hash := {}
Loop % array1.maxIndex()
hash[array1[A_Index]] := array2[A_Index]
MsgBox % hash["apple"] "`n" hash["two"]</
=={{header|AWK}}==
Awk arrays are used for both lists and hash maps.
<!-- http://ideone.com/MsdNUc -->
<
BEGIN {
if(!list1) list1="one two three"
Line 132 ⟶ 424:
for(i in c) print i,c[i]
}</
{{out}}
Line 146 ⟶ 438:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
Line 165 ⟶ 457:
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</
=={{header|Bracmat}}==
<
& 2 3 fruit:?arr2
& new$hash:?H
Line 178 ⟶ 470:
& (H..forall)$out
& ;
</syntaxhighlight>
{{out}}
<pre>apple.fruit
Line 185 ⟶ 477:
=={{header|Brat}}==
<
h = [:]
keys.each_with_index { key, index |
Line 194 ⟶ 486:
}
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</
=={{header|C}}==
Line 201 ⟶ 493:
following implementation tries to be somewhat generic to facilitate using alternative key and
value types.
<
#include <stdlib.h>
#include <string.h>
Line 315 ⟶ 607:
}
return 0;
}</
=={{header|C sharp}}==
===C# 1.0===
<
{
static void Main()
Line 363 ⟶ 627:
}
}
}</
<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:
<
===Modern===
Line 375 ⟶ 639:
<code>Enumerable.Zip</code> truncates the longer of its arguments.
<
static class Program
Line 388 ⟶ 652:
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}</
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}</syntaxhighlight>
{{libheader|range-v3}}
<syntaxhighlight lang="cpp">#include <range/v3/view/zip.hpp>
#include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "foo", "bar", "baz" };
std::unordered_map<std::string, std::string> hash(ranges::view::zip(keys, vals));
}
</syntaxhighlight>
=={{header|Ceylon}}==
<
value keys = [1, 2, 3];
value items = ['a', 'b', 'c'];
value hash = map(zipEntries(keys, items));
}</
=={{header|Clojure}}==
<
=={{header|Coco}}==
<
values = <[red yellow orange purple]>
object = new
@[keys[i]] = values[i] for i til keys.length</
=={{header|CoffeeScript}}==
<
keys = ['a','b','c']
values = [1,2,3]
map = {}
map[key] = values[i] for key, i in keys
</syntaxhighlight>
=={{header|ColdFusion}}==
<
function makeHash(keyArray, valueArray) {
var x = 1;
Line 429 ⟶ 721:
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
</cfscript></
=={{header|Common Lisp}}==
<
(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))</
Or, using cl:loop:
<
(loop initially (assert (= (length vector-1) (length vector-2)))
with table = (make-hash-table :test test :size (length vector-1))
Line 448 ⟶ 740:
for v across vector-2
do (setf (gethash k table) v)
finally (return table)))</
In Common Lisp terminology, a vector is a one-dimensional array.
Line 454 ⟶ 746:
=={{header|Crystal}}==
<
vals = (1..26).to_a # => 1, 2, 3 ... 26
hash = Hash.zip(keys, vals)
p hash</
<pre>
Line 465 ⟶ 757:
=={{header|D}}==
<
import std.array, std.range;
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}</
=={{header|Déjà Vu}}==
<
local :h_values [ 1 2 3 ]
local :h {}
for item in h_keys:
set-to h item pop-from h_values
</syntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">
program Hash_from_two_arrays;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Collections;
type
THash = TDictionary<string, Integer>;
THashHelper = class helper for THash
procedure AddItems(keys: TArray<string>; values: TArray<Integer>);
end;
{ THashHelper }
procedure THashHelper.AddItems(keys: TArray<string>; values: TArray<Integer>);
var
i: Integer;
begin
Assert(length(keys) = Length(values), 'Keys and values, must have the same size.');
for i := 0 to High(keys) do
AddOrSetValue(keys[i], values[i]);
end;
var
hash: TDictionary<string, Integer>;
i: integer;
key: string;
begin
hash := TDictionary<string, Integer>.Create();
hash.AddItems(['a', 'b', 'c'], [1, 2, 3]);
for key in hash.Keys do
Writeln(key, ' ', hash[key]);
hash.Free;
readln;
end.
</syntaxhighlight>
{{out}}
<pre>
b 2
a 1
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}}==
<
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)</
=={{header|EchoLisp}}==
<
(lib 'hash)
Line 497 ⟶ 867:
(hash-ref H 'elvis)
→ "the king"
</syntaxhighlight>
=={{header|Elixir}}==
<
[: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}</
=={{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">
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).
</syntaxhighlight>
=={{header|F Sharp|F#}}==
<
=={{header|Factor}}==
<
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</
=={{header|Falcon}}==
<
keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]
</syntaxhighlight>
=={{header|Fantom}}==
<
class Main
{
Line 546 ⟶ 935:
}
}
</syntaxhighlight>
=={{header|FreeBASIC}}==
<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 hash(Lbound(keys) To Ubound(keys))
Dim As Integer i, temp
For i = Lbound(values) To Ubound(values)
temp = Val(keys(i))
hash(temp) = values(i)
Next i
For i = Lbound(hash) To Ubound(hash)
Print keys(i); " "; hash(i)'; " "; i
Next i
Sleep</syntaxhighlight>
{{out}}
<pre> 1 one
2 two
3 three
4 four
5 five</pre>
=={{header|Frink}}==
There is a built-in dictionary/hash constructor that takes two arrays as input.
<
a = new dict[["a", "b", "c"], [1, 2, 3]]
</syntaxhighlight>
=={{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]'''
<
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Line 570 ⟶ 1,009:
Next
End</
Output:
<pre>
Line 582 ⟶ 1,021:
=={{header|Go}}==
<
import "fmt"
Line 594 ⟶ 1,033:
}
fmt.Println(hash)
}</
{{out}}
<pre>
Line 602 ⟶ 1,041:
=={{header|Groovy}}==
<
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
}</
Alternative Version:
<
Test:
<
=={{header|Harbour}}==
<
LOCAL hash := { => }
LOCAL i, j
Line 622 ⟶ 1,061:
FOR EACH i, j IN arr1, arr2
hash[ i ] := j
NEXT</
=={{header|Haskell}}==
{{works with|GHC|GHCi|6.6}}
<
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]</
=={{header|Huginn}}==
<
main() {
Line 639 ⟶ 1,078:
values = ['a', 'b', 'c'];
hash = materialize( zip( key, values ), lookup );
}</
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main(arglist) #: demonstrate hash from 2 lists
Line 653 ⟶ 1,092:
write(ximage(T)) # show result
end</
=={{header|Ioke}}==
<
=={{header|J}}==
Line 664 ⟶ 1,103:
'''Solution:'''
<
'''For example:'''
<
vals=: > ;:'zero one two three four five six seven eight nine'
hash=: vals {~ keys&i.
Line 685 ⟶ 1,124:
six
seven
two</
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}}==
<
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
Line 698 ⟶ 1,137:
hash.put(keys[i], vals[i]);
}
}</
=={{header|JavaScript}}==
===Iterative===
<
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
Line 710 ⟶ 1,149:
map[ keys[i] ] = values[i];
}
</syntaxhighlight>
===Iterative Using Foreach===
<
function arrToObj(keys, vals) {
var map = {};
Line 721 ⟶ 1,160:
return map;
}
</syntaxhighlight>
===Using Reduce===
<
function arrToObj(keys, vals) {
return keys.reduce(function(map, key, index) {
Line 731 ⟶ 1,170:
}, {});
}
</syntaxhighlight>
=={{header|jq}}==
jq only supports hashing of strings. In the following, accordingly, we assume that
one array (keys) is an array of strings.
<
# and values taken from the input array in turn.
# "keys" must be an array of strings.
Line 747 ⟶ 1,186:
( {}; . + { (keys[$i]) : $values[$i] });
[1,2,3] | hash( ["a","b","c"] )</
{{Out}}
<
{
"a": 1,
"b": 2,
"c": 3
}</
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:<
"1": 10,
"2": 20,
"3": 30
}</
=={{header|Jsish}}==
From Javascript.
<
function hashTwo(k:array, v:array):object {
var hash = {};
Line 784 ⟶ 1,223:
hashTwo([], []) ==> {}
=!EXPECTEND!=
*/</
{{out}}
<pre>prompt$ jsish -u hashTwo.jsi
Line 794 ⟶ 1,233:
'''Using comprehension''':
<
v = [1, 2, 3]
Dict(ki => vi for (ki, vi) in zip(k, v))</
'''Using constructor''':
<syntaxhighlight lang
'''Specifying types''':
<
=={{header|K}}==
The keys in a dictionary must be a symbol.
<
b: 0 1 2
Line 816 ⟶ 1,255:
d[`one]
1</
Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols).
<
split:{1_'(&x=y)_ x:y,x}
vals:split["zero one two three four five six seven eight nine";" "]
Line 838 ⟶ 1,277:
$d[s 1] / leading "$" converts back to string
"one"</
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 848 ⟶ 1,287:
val hash = mapOf(*names.zip(ages).toTypedArray())
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}</
{{out}}
Line 857 ⟶ 1,296:
Donald aged 70
</pre>
=={{header|Lang5}}==
<syntaxhighlight lang="lang5">: >table 2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table</syntaxhighlight>
=={{header|langur}}==
=== the easy way ===
<syntaxhighlight lang="langur">writeln(hash fw/a b c d/, [1, 2, 3, 4])
</syntaxhighlight>
Note that fw/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.
<syntaxhighlight lang="langur">val .new = foldfrom(
fn(.hash, .key, .value) more .hash, {.key: .value},
hash(), fw/a b c d/, [1, 2, 3, 4],
)
writeln .new</syntaxhighlight>
{{out}}
<pre>{"d": 4, "a": 1, "b": 2, "c": 3}</pre>
=={{header|Lasso}}==
<
array1 = array('a', 'b', 'c'),
array2 = array(1, 2, 3),
Line 869 ⟶ 1,331:
}
#hash</
-> map(a = 1, b = 2, c = 3)
=={{header|LFE}}==
<
(vals (list '"foo data" '"bar data" '"baz data"))
(tuples (: lists zipwith
Line 902 ⟶ 1,341:
(my-dict (: dict from_list tuples)))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))
</syntaxhighlight>
=={{header|Lingo}}==
<
values = [1,2,3]
Line 915 ⟶ 1,354:
put props
-- ["a": 1, "b": 2, "c": 3]</
=={{header|LiveCode}}==
<
put 10,20,30 into list2
split list1 using comma
Line 929 ⟶ 1,368:
-- ouput
-- a:10,b:20,c:30</
=={{header|Lua}}==
<
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckAll {
Module CheckVectorType {
Line 967 ⟶ 1,405:
}
CheckAll
</syntaxhighlight>
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">
Module Checkit {
Function MakeHash(&a$(), &b$()) {
Line 1,014 ⟶ 1,452:
}
Checkit
</syntaxhighlight>
=={{header|Maple}}==
<
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
Line 1,028 ⟶ 1,466:
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three</
=={{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===
<
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
Line 1,047 ⟶ 1,485:
end
end
end</
{{out}}
<pre>>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27])
Line 1,073 ⟶ 1,511:
=={{header|MiniScript}}==
<
values = ["little", "miss", "muffet"]
Line 1,081 ⟶ 1,519:
end for
print d</
{{out}}
<pre>{"bar": "miss", "foo": "little", "val": "muffet"}</pre>
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
Line 1,105 ⟶ 1,543:
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)</
{{out}}
Line 1,115 ⟶ 1,553:
Hashed key: 4 Value: 9
Hashed key: 737454 Value: zero</pre>
=={{header|Nemerle}}==
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections.NCollectionsExtensions;
module AssocArray
{
Main() : void
{
def list1 = ["apples", "oranges", "bananas", "kumquats"];
def list2 = [13, 34, 12];
def inventory = Hashtable(ZipLazy(list1, list2));
foreach (item in inventory)
WriteLine("{0}: {1}", item.Key, item.Value);
}
}</syntaxhighlight>
=={{header|NetRexx}}==
=== REXX Style ===
{{trans|REXX}}
<
* 04.11.2012 Walter Pachl derived from REXX
**********************************************************************/
Line 1,140 ⟶ 1,596:
Say ' 'keys
Parse Ask z
Say z '->' value[z]</
=== Java Collections ===
NetRexx has access to Java's Collection objects too.
<
options replace format comments java crossref symbols nobinary
Line 1,185 ⟶ 1,641:
return
</syntaxhighlight>
=={{header|Nim}}==
<
let keys = @['a','b','c']
let values = @[1, 2, 3]
let table = toTable zip(keys, values)</
=={{header|Oberon-2}}==
Works with oo2c version 2
<
MODULE HashFromArrays;
IMPORT
Line 1,276 ⟶ 1,689:
Do;
END HashFromArrays.
</syntaxhighlight>
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
use Structure;
bundle Default {
class HashOfTwo {
function : Main(args : System.String[]) ~ Nil {
keys := ["1", "2", "3"];
vals := ["a", "b", "c"];
hash := StringHash->New();
each(i : vals) {
hash->Insert(keys[i], vals[i]->As(Base));
};
}
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
<syntaxhighlight lang="objc">NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</syntaxhighlight>
=={{header|OCaml}}==
The idiomatic solution uses lists rather than arrays.
<
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;
List.iter2 (Hashtbl.add hash) keys vals;;</
The solution is similar with arrays.
<
and vals = [| 16384; 32768; 65536 |]
and hash = Hashtbl.create 0;;
Array.iter2 (Hashtbl.add hash) keys vals;;</
In either case, an exception is raised if the inputs are different lengths.
Line 1,299 ⟶ 1,737:
If you want to use functional binary search trees instead of hash tables:
<
let keys = [ "foo"; "bar"; "baz" ]
Line 1,305 ⟶ 1,743:
and map = StringMap.empty;;
let map = List.fold_right2 StringMap.add keys vals map;;</
=={{header|ooRexx}}==
<
array2 = .array~of("555-9862", "555-5309", "555-6666")
Line 1,320 ⟶ 1,758:
Say 'Enter a name'
Parse Pull name
Say name '->' hash[name]</
{{out}}
<pre>Enter a name
Line 1,327 ⟶ 1,765:
=={{header|Oz}}==
<
fun {ZipRecord Keys Values}
{List.toRecord unit {List.zip Keys Values MakePair}}
Line 1,336 ⟶ 1,774:
end
in
{Show {ZipRecord [a b c] [1 2 3]}}</
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{libheader|contnrs}}
<
uses
Line 1,362 ⟶ 1,800:
writeln ('Length of hash table: ', hash.Count);
hash.Destroy;
end.</
{{out}}
<pre>% ./HashFromTwoArrays
Line 1,369 ⟶ 1,807:
=={{header|Perl}}==
<
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;</
Alternatively, using {{libheader|List::MoreUtils}}:
<
my %hash = zip @keys, @vals;</
=={{header|Phix}}==
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out.
<!--<syntaxhighlight lang="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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">dict</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">keyarray</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">keyarray</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">valuearray</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">dict</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- setd(keyarray[i],i,dict)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">dict</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">keyarray</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"two"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">valuearray</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #004600;">PI</span><span style="color: #0000FF;">}</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">dict</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">make_hash</span><span style="color: #0000FF;">(</span><span style="color: #000000;">keyarray</span><span style="color: #0000FF;">,</span><span style="color: #000000;">valuearray</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: #000000;">1</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: #008000;">"two"</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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,427 ⟶ 1,843:
2
3.141592654
</pre>
=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
def getd /# array key -- array data #/
swap 1 get rot find nip
dup if
swap 2 get rot get nip
else
drop "Unfound"
endif
enddef
( ( 1 "two" PI ) ( "one" 2 PI ) ) /# keys / data #/
1 getd print nl
"two" getd print nl
PI getd tostr print nl
3 getd print</syntaxhighlight>
{{out}}
<pre>
one
2
3.141592653589793
Unfound
</pre>
=={{header|PHP}}==
{{works with|PHP|5}}
<
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);</
{{works with|PHP|4}}
<
$values = array(1, 2, 3);
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
}</
=={{header|Picat}}==
<syntaxhighlight lang="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).</syntaxhighlight>
{{out}}
<pre>(map)[d = 4,c = 3,b = 2,a = 1,e = 5]</pre>
=={{header|PicoLisp}}==
<
(mapc println
(mapcar cons Keys Values) ) )</
{{out}}
<pre>(one . 1)
Line 1,454 ⟶ 1,907:
=={{header|Pike}}==
Any data type can be used as indices (keys) and values.
<syntaxhighlight 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>
{{Out}}
<pre>
Line 1,471 ⟶ 1,924:
=={{header|Pop11}}==
<
vars vals = { 2 3 valb valc};
vars i;
Line 1,479 ⟶ 1,932:
for i from 1 to length(keys) do
vals(i) -> ht(keys(i));
endfor;</
=={{header|PostScript}}==
{{libheader|initlib}}
<
% push our arrays
[/a /b /c /d /e] [1 2 3 4 5]
Line 1,490 ⟶ 1,943:
% show that we have created the hash
{= =} forall
</syntaxhighlight>
=={{header|PowerShell}}==
<
$h = @{}
if ($keys.Length -ne $values.Length) {
Line 1,504 ⟶ 1,958:
}
return $h
}</
=={{header|Prolog}}==
<
:-dynamic hash/2.
Line 1,526 ⟶ 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).</
=={{header|PureBasic}}==
<
Dim vals.s(3)
NewMap Hash.s()
Line 1,540 ⟶ 1,994:
ForEach Hash()
Debug Hash()
Next</
=={{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):
<
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}</
{{works with|Python|2.2+}}
<
values = [1, 2, 3]
hash = dict(zip(keys, values))
Line 1,556 ⟶ 2,010:
# Lazily, Python 2.3+, not 3.x:
from itertools import izip
hash = dict(izip(keys, values))</
{{works with|Python|2.0+}}
<
values = [1, 2, 3]
hash = {}
for k,v in zip(keys, values):
hash[k] = v</
The original (Ruby) example uses a range of different types as keys. Here is similar in python (run at the shell):
<
def __hash__(self):
return id(self) ^ 0xBEEF
Line 1,606 ⟶ 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</
=={{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]].
<
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
Line 1,617 ⟶ 2,071:
values["Sam Doe"] # vals["Sam Doe"]
# Get all keys corresponding to a value
names(values)[values==152] # "John Smith" "Sandra Dee"</
=={{header|Racket}}==
<
(make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))</
Alternatively:
<
(define (connect keys vals) (for/hash ([k keys] [v vals]) (values k v)))
;; Example:
(connect #("a" "b" "c" "d") #(1 2 3 4))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Using the "zipwith" meta-operator on the <tt>=></tt> pair composer:
{{works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" line>my @keys = <a b c d e>;
my @values = ^5;
my %hash = @keys Z=> @values;
#Alternatively, by assigning to a hash slice:
%hash{@keys} = @values;
# Or to create an anonymous hash:
%( @keys Z=> @values );
# All of these zip forms trim the result to the length of the shorter of their two input lists.
# If you wish to enforce equal lengths, you can use a strict hyperoperator instead:
quietly # suppress warnings about unused hash
{ @keys »=>« @values }; # Will fail if the lists differ in length</syntaxhighlight>
=={{header|Raven}}==
<
$keys $vals combine as $hash</
=={{header|REXX}}==
This REXX version allows multiple keys for a value, the keys are case sensitive.
<
key.= /*names of the nine regular polygons. */
vals= 'triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon'
Line 1,647 ⟶ 2,127:
hash.='───(not defined)───' /* [↑] blanks added to humorous keys */
/* just because it looks prettier.*/
do k=1 while key.k\==''
call hash vals,key.k
end /*k*/
parse arg query . /*obtain what was specified on the C.L.*/
if query\=='' then
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Line 1,660 ⟶ 2,139:
hash.map= word(@val, j)
end /*j*/
return</
{{out|output|text= when using the input value of: <tt> phive </tt>}}
<pre>
Line 1,671 ⟶ 2,150:
=={{header|Ring}}==
<
# Project : Hash from two arrays
Line 1,686 ⟶ 2,165:
see c[i] + " " + i + nl
next
</syntaxhighlight>
Output:
<pre>
Line 1,692 ⟶ 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}}==
<
keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]
Line 1,705 ⟶ 2,201:
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123
</syntaxhighlight>
In Ruby 2.1 the method "to_h" was introduced:
<
vals = ['ibm', 'devil', 123]
keys.zip(vals).to_h</
=={{header|Rust}}==
<
fn main() {
Line 1,722 ⟶ 2,218:
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
}</
=={{header|Sather}}==
<
zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
pre k.size = e.size
Line 1,747 ⟶ 2,243:
end;
end;</
=={{header|Scala}}==
<
val values = Array("A", "B", "C") // Array mixed with List
val map = keys.zip(values).toMap // and other Seq are possible.
Line 1,756 ⟶ 2,252:
// Testing
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
println("Successfully completed without errors.")</
=={{header|Scheme}}==
=== Using [http://srfi.schemers.org/srfi-69/srfi-69.html SRFI 69]
<
(apply alist->hash-table (map cons keys values) rest))</
=== Using association lists ===
<syntaxhighlight lang="scheme">;; Using SRFI-1, R6RS, or R7RS association lists.
;; Because the task calls for ‘arrays’, I start with actual arrays
;; rather than lists.
(define array1 (vector "a" "b" "c" "d"))
(define array2 (vector 1 2 3 4))
;; Making the hash is just a simple list operation.
(define dictionary (map cons (vector->list array1)
(vector->list array2)))
;; Now you can look up associations with assoc.
(write (assoc "b" dictionary)) (newline)
(write (assoc "d" dictionary)) (newline)
;; USING CHICKEN 5 SCHEME, OUTPUT FROM EITHER
;; ‘csc -R srfi-1 thisprog.scm && ./thisprog’
;; OR ‘csc -R r7rs thisprog.scm && ./thisprog’,
;; AND ALSO TESTED IN CHEZ SCHEME (R6RS):
;;
;; ("b" . 2)
;; ("d" . 4)
;;</syntaxhighlight>
=== Using [[Associative_array/Creation#A_persistent_associative_array_from_scratch|''persistent'' associative arrays]] ===
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.
<syntaxhighlight lang="scheme">(import (associative-arrays))
;; Because the task calls for ‘arrays’, I start with actual arrays
;; rather than lists.
(define array1 (vector "a" "b" "c" "d"))
(define array2 (vector 1 2 3 4))
(define (silly-hashfunc s)
(define h 1234)
(do ((i 0 (+ i 1)))
((= i (string-length s)))
(set! h (+ h (char->integer (string-ref s i)))))
(sqrt (/ (* h 101) 9.80665)))
;; Here is the making of the associative array:
(define dictionary (assoc-array silly-hashfunc))
(vector-for-each (lambda (key data)
(set! dictionary
(assoc-array-set dictionary key data)))
array1 array2)
(display "Looking up \"b\" and \"d\": ")
(write (assoc-array-ref dictionary "b"))
(display " ")
(write (assoc-array-ref dictionary "d"))
(newline)
;; Output:
;;
;; Looking up "b" and "d": 2 4
;;</syntaxhighlight>
Side note: association lists can be used in either a persistent or non-persistent manner.
=={{header|Seed7}}==
<
const type: numericHash is hash [string] integer;
Line 1,779 ⟶ 2,338:
myHash @:= [keyList[number]] valueList[number];
end for;
end func;</
=={{header|SenseTalk}}==
<
set keyList to ["red", "green", "blue"]
set valueList to [150,0,128]
Line 1,793 ⟶ 2,352:
--> (blue:"128", green:"0", red:"150")
</syntaxhighlight>
=={{header|Sidef}}==
<
var vals = [1, 2, 3]
var hash = Hash()
hash{keys...} = vals...
say hash</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
dictionaryWithValues: array [ |d|
d := Dictionary new.
Line 1,818 ⟶ 2,377:
({ 'red' . 'one' . 'two' }
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</
{{works with|Smalltalk/X}}
{{works with|VisualWorks Smalltalk}}
<
withKeys:#('one' 'two' 'three')
andValues:#('eins' 'zwei' 'drei')</
{{works with|Smalltalk/X}}
<
=={{header|SNOBOL4}}==
Line 1,835 ⟶ 2,394:
{{works with|CSnobol}}
<
keys = array(5); vals = array(5)
ks = 'ABCDE'; vs = '12345'
Line 1,850 ⟶ 2,409:
str = str ch ':' hash<ch> ' ' :(tloop)
out output = str
end</
{{out}}
Line 1,856 ⟶ 2,415:
=={{header|Sparkling}}==
<
let vals = { 13, 37, 42 };
var hash = {};
for var i = 0; i < sizeof keys; i++ {
hash[keys[i]] = vals[i];
}</
=={{header|Standard ML}}==
Line 1,867 ⟶ 2,426:
Using functional binary search trees instead of hash tables:
<
type ord_key = string
val compare = String.compare
Line 1,876 ⟶ 2,435:
and myMap = StringMap.empty;
val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));</
{{works with|SML/NJ}}
Using hash tables:
<
val keys = [ "foo", "bar", "baz" ]
Line 1,887 ⟶ 2,446:
and hash = HashTable.mkTable (HashString.hashString, op=) (42, NotFound);
ListPair.appEq (HashTable.insert hash) (keys, vals);</
=={{header|Swift}}==
{{works with|Swift|1.2+}}
<
let vals = [1,2,3]
var hash = [String: Int]()
for (key, val) in zip(keys, vals) {
hash[key] = val
}</
=={{header|Tcl}}==
Line 1,905 ⟶ 2,464:
"<i>lists</i> of equal length",
then the task might look like this:
<
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set arr($a) $b }
parray arr</
{{out}}
<pre>
Line 1,919 ⟶ 2,478:
Alternatively, a dictionary could be used: <!-- http://ideone.com/6lI4k5 -->
<
set keys [list fred bob joe]
Line 1,928 ⟶ 2,487:
}
puts "jobs: [dict get $jobs]"</
{{out}}
<pre>
Line 1,938 ⟶ 2,497:
===One-liner, using quasiquoted hash syntax===
<
#H(() (c 3) (b 2) (a 1))</
===One-liner, using <code>hash-construct</code> function===
<
#H(() (c 3) (b 2) (a 1))</
===Explicit construction and stuffing===
<
(let ((table (hash . hash-args)))
(mapcar (do sethash table) vec1 vec2)
table))
(prinl (hash-from-two #(a b c) #(1 2 3)))</
<pre>$ ./txr hash-from-two.tl
#H(() (c 3) (b 2) (a 1))</pre>
=={{header|UNIX Shell}}==
{{works with|Bash|4}}
<syntaxhighlight lang="bash">keys=( foo bar baz )
values=( 123 456 789 )
declare -A hash
for (( i = 0; i < ${#keys[@]}; i++ )); do
hash["${keys[i]}"]=${values[i]}
done
for key in "${!hash[@]}"; do
printf "%s => %s\n" "$key" "${hash[$key]}"
done</syntaxhighlight>
{{out}}
<pre>bar => 456
baz => 789
foo => 123</pre>
=={{header|UnixPipes}}==
Using a sorted file as an associative array (see Creating an associative array for usage.)
<
apple
boy
Line 1,977 ⟶ 2,555:
KEYS
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</
=={{header|Ursala}}==
There is a built-in operator for this.
<
values = <12354,145430,76748>
hash_function = keys-$values</
test program:
<
test = hash_function* <'bar','baz','foo','bar'></
{{out}}
<pre><145430,76748,12354,145430></pre>
Line 2,013 ⟶ 2,572:
=={{header|Vala}}==
{{libheader|Gee}}
<
using Gee;
Line 2,029 ⟶ 2,588:
}
}
</syntaxhighlight>
=={{header|VBScript}}==
Line 2,035 ⟶ 2,594:
VBScript (and Visual Basic in general) calls hashes "dictionary objects".
<
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,043 ⟶ 2,602:
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")</
{{out}} (in message boxes):
Line 2,065 ⟶ 2,624:
and the order that the arguments are passed to the <code>Add</code> method.
<
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
Line 2,073 ⟶ 2,632:
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")</
=={{header|WDTE}}==
<
let s => import 'stream';
Line 2,086 ⟶ 2,645:
set scope k v;
)
;</
'''Example:'''
<
['a'; 'b'; 'c']
[1; 2; 3]
Line 2,099 ⟶ 2,658:
-> s.collect
-- io.writeln io.stdout
;</
{{out}}
<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]
mut hash := map[string]int{}
for i, key in keys {
hash[key] = vals[i]
}
println(hash)
}</syntaxhighlight>
{{out}}
<pre>
{'a': 1, 'b': 2, 'c': 3}
</pre>
=={{header|Wortel}}==
Wortel has an inbuilt operator to do this: <code>@hash</code>.
<
This function can also be defined as:
<syntaxhighlight lang
Example:
<
hash ^(@obj @zip)
!!hash ["a" "b" "c"] [1 2 3]
}</
{{out|Returns}}
<pre>{a 1 b 2 c 3}</pre>
=={{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.
<syntaxhighlight lang="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)</syntaxhighlight>
{{out}}
<pre>
{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}}==
<
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println();</
{{out}}
<pre>D(a:1,b:2,c:3,d:4)
|