Hash from two arrays: Difference between revisions
→{{header|Ruby}}: Make pre-1.8.7 code work when key is an Array. Rename Array#to_hash to Array#zip_hash, so that Hash.try_convert(ary) never calls Array#to_hash by mistake. |
PascalABC.NET |
||
(209 intermediate revisions by 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Basic language learning}} |
|||
{{task|Basic language learning}}Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) |
|||
[[Category:Data Structures]] |
|||
{{omit from|BASIC}} <!-- Does not have hash tables or other map structures. --> |
|||
{{omit from|PowerBASIC}} |
|||
{{omit from|TI-83 BASIC}} |
|||
{{omit from|TI-89 BASIC}} |
|||
;Task: |
|||
Using two Arrays of equal length, create a Hash object |
|||
where the elements from one array (the keys) are linked |
|||
to the elements of the other (the values) |
|||
;Related task: |
|||
* [[Associative arrays/Creation]] |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
{{trans|Python}} |
|||
<syntaxhighlight lang="11l">V keys = [‘a’, ‘b’, ‘c’] |
|||
V values = [1, 2, 3] |
|||
V hash_ = Dict(zip(keys, values)) |
|||
print(hash_)</syntaxhighlight> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
< |
<syntaxhighlight lang="actionscript">package |
||
{ |
{ |
||
public class MyClass |
public class MyClass |
||
Line 16: | Line 39: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|GNAT|GPL 2007}} |
{{works with|GNAT|GPL 2007}} |
||
< |
<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 62: | Line 85: | ||
end loop; |
end loop; |
||
end Hash_Map_Test;</ |
end Hash_Map_Test;</syntaxhighlight> |
||
=={{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}}== |
=={{header|Argile}}== |
||
{{works with|Argile|1.1.0}} |
{{works with|Argile|1.1.0}} |
||
< |
<syntaxhighlight lang="argile">use std, array, hash |
||
let keys = @["hexadecimal" "decimal" "octal" "binary"] |
let keys = @["hexadecimal" "decimal" "octal" "binary"] |
||
Line 73: | 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</ |
del hash hash</syntaxhighlight> |
||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">h: dictionary.raw flatten couple [a b c d] [1 2 3 4] |
|||
print h</syntaxhighlight> |
|||
{{out}} |
|||
<pre>[a:1 b:2 c:3 d:4]</pre> |
|||
=={{header|AutoHotkey}}== |
|||
<syntaxhighlight lang="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"]</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 --> |
|||
<lang awk>$ awk 'BEGIN{split("one two three",a); |
|||
<syntaxhighlight lang="awk"># usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk |
|||
split("1 2 3",b); |
|||
BEGIN { |
|||
for(i=1;i in a;i++){c[a[i]]=b[i]}; |
|||
if(!list1) list1="one two three" |
|||
for(i in c)print i,c[i] |
|||
if(!list2) list2="1 2 3" |
|||
}' |
|||
split(list1, a); |
|||
split(list2, b); |
|||
for(i=1;i in a;i++) { c[a[i]] = b[i] }; |
|||
for(i in c) print i,c[i] |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
three 3 |
three 3 |
||
two 2 |
two 2 |
||
one 1 |
one 1 |
||
</pre> |
|||
=={{header|BASIC256}}== |
|||
''Solution is at [[Associative_array/Creation#BASIC256]]''. |
|||
=={{header|BBC BASIC}}== |
|||
{{works with|BBC BASIC for Windows}} |
|||
<syntaxhighlight lang="bbcbasic"> DIM array1$(4) : array1$() = "0", "1", "2", "3", "4" |
|||
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four" |
|||
FOR index% = 0 TO DIM(array1$(),1) |
|||
PROCputdict(mydict$, array2$(index%), array1$(index%)) |
|||
NEXT |
|||
PRINT FNgetdict(mydict$, "3") |
|||
END |
|||
DEF PROCputdict(RETURN dict$, value$, key$) |
|||
IF dict$ = "" dict$ = CHR$(0) |
|||
dict$ += key$ + CHR$(1) + value$ + CHR$(0) |
|||
ENDPROC |
|||
DEF FNgetdict(dict$, key$) |
|||
LOCAL I%, J% |
|||
I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1)) |
|||
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2 |
|||
J% = INSTR(dict$, CHR$(0), I%) |
|||
= MID$(dict$, I%, J% - I%)</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
|||
<syntaxhighlight lang="bracmat"> two three apple:?arr1 |
|||
& 2 3 fruit:?arr2 |
|||
& new$hash:?H |
|||
& whl |
|||
' ( !arr1:%?k ?arr1 |
|||
& !arr2:%?v ?arr2 |
|||
& (H..insert)$(!k.!v) |
|||
) |
|||
& (H..forall)$out |
|||
& ; |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre>apple.fruit |
|||
three.3 |
|||
two.2</pre> |
|||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">zip = { keys, values | |
||
h = [:] |
h = [:] |
||
keys.each_with_index { key, index | |
keys.each_with_index { key, index | |
||
Line 96: | Line 486: | ||
} |
} |
||
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</ |
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
There likely exist libraries that can be for creating hashes that are better than the following |
There likely exist libraries that can be used for creating hashes that are better than the following |
||
implementation. There are also better functions for obtaining hash values from strings. The |
implementation. There are also better functions for obtaining hash values from strings. The |
||
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. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 217: | Line 607: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C |
=={{header|C sharp}}== |
||
===C# 1.0=== |
|||
By strict definition a std::map is not a hash, but it provides the same functionality. The C++-200x update to the C++ standard is incorporating hashes. When they are standardized the code below can change ''std::map'' to ''std::unordered_map'' and this will technically be a hash table. The core idea, turning two sequences into an associative mapping, is valid either way. |
|||
<syntaxhighlight lang="csharp">static class Program |
|||
{ |
|||
static void Main() |
|||
{ |
|||
System.Collections.Hashtable h = new System.Collections.Hashtable(); |
|||
string[] keys = { "foo", "bar", "val" }; |
|||
<lang cpp>#include <map> |
|||
string[] values = { "little", "miss", "muffet" }; |
|||
#include <string> |
|||
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); |
|||
int |
|||
main( int argc, char* argv[] ) |
|||
{ |
|||
std::string keys[] = { "1", "2", "3" } ; |
|||
std::string vals[] = { "a", "b", "c" } ; |
|||
std::map< std::string, std::string > hash ; |
|||
for( int i = 0 ; i < 3 ; i++ ) |
|||
{ |
|||
hash[ keys[i] ] = vals[i] ; |
|||
} |
|||
}</lang> |
|||
for (int i = 0; i < keys.Length; i++) |
|||
Alternatively: |
|||
{ |
|||
<lang cpp>#include <map> // for std::map |
|||
h.Add(keys[i], values[i]); |
|||
#include <algorithm> // for std::transform |
|||
} |
|||
#include <string> // for std::string |
|||
} |
|||
#include <utility> // for std::make_pair |
|||
}</syntaxhighlight> |
|||
<code>Hashtable.Add</code> throws an exception when a key already exists. |
|||
int main() |
|||
An alternative method to add entries is to use the indexer setter, which replaces the old value associated with a key, if any: |
|||
<syntaxhighlight lang="csharp">h[keys[i]] = values[i];</syntaxhighlight> |
|||
===Modern=== |
|||
Uses <code>System.Collections.Generic.Dictionary<TKey, TValue></code>, <code>Enumerable.ToDictionary</code> from LINQ, extension method syntax, and lambda expressions. |
|||
<code>Enumerable.Zip</code> truncates the longer of its arguments. |
|||
<syntaxhighlight lang="csharp">using System.Linq; |
|||
static class Program |
|||
{ |
{ |
||
static void Main() |
|||
std::string keys[] = { "one", "two", "three" }; |
|||
{ |
|||
std::string vals[] = { "foo", "bar", "baz" }; |
|||
string[] keys = { "foo", "bar", "val" }; |
|||
string[] values = { "little", "miss", "muffet" }; |
|||
var h = keys |
|||
std::map<std::string, std::string> hash; |
|||
.Zip(values, (k, v) => (k, v)) |
|||
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|C++}}== |
|||
std::transform(keys, keys+3, |
|||
<syntaxhighlight lang="cpp">#include <unordered_map> |
|||
vals, |
|||
#include <string> |
|||
std::inserter(hash, hash.end()), |
|||
std::make_pair<std::string, std::string>); |
|||
}</lang> |
|||
int main() |
|||
=={{header|C sharp}}== |
|||
{ |
|||
<lang csharp>System.Collections.HashTable h = new System.Collections.HashTable(); |
|||
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}} |
|||
string[] arg_keys = {"foo","bar","val"}; |
|||
<syntaxhighlight lang="cpp">#include <range/v3/view/zip.hpp> |
|||
string[] arg_values = {"little", "miss", "muffet"}; |
|||
#include <unordered_map> |
|||
#include <string> |
|||
//Some basic error checking |
|||
int arg_length = 0; |
|||
int main() |
|||
if ( arg_keys.Length == arg_values.Length ) { |
|||
{ |
|||
arg_length = arg_keys.Length; |
|||
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}}== |
|||
for( int i = 0; i < arg_length; i++ ){ |
|||
<syntaxhighlight lang="ceylon">shared void run() { |
|||
h.add( arg_keys[i], arg_values[i] ); |
|||
value keys = [1, 2, 3]; |
|||
}</lang> |
|||
value items = ['a', 'b', 'c']; |
|||
value hash = map(zipEntries(keys, items)); |
|||
}</syntaxhighlight> |
|||
=={{header|Clojure}}== |
|||
Alternate way of adding values |
|||
<syntaxhighlight lang="lisp">(zipmap [\a \b \c] [1 2 3])</syntaxhighlight> |
|||
=={{header|Coco}}== |
|||
<lang csharp>for( int i = 0; i < arg_length; i++ ){ |
|||
<syntaxhighlight lang="coco">keys = <[apple banana orange grape]> |
|||
h[ arg_keys[i] ] = arg_values[i]; |
|||
values = <[red yellow orange purple]> |
|||
}</lang> |
|||
object = new |
|||
=={{header|Clojure}}== |
|||
@[keys[i]] = values[i] for i til keys.length</syntaxhighlight> |
|||
<lang lisp>(zipmap [\a \b \c] [1 2 3])</lang> |
|||
=={{header|CoffeeScript}}== |
|||
<syntaxhighlight lang="coffeescript"> |
|||
keys = ['a','b','c'] |
|||
values = [1,2,3] |
|||
map = {} |
|||
map[key] = values[i] for key, i in keys |
|||
</syntaxhighlight> |
|||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="coldfusion"><cfscript> |
||
function makeHash(keyArray, valueArray) { |
function makeHash(keyArray, valueArray) { |
||
var x = 1; |
var x = 1; |
||
Line 297: | Line 721: | ||
valueArray = [1, 2, 3]; |
valueArray = [1, 2, 3]; |
||
map = makeHash(keyArray, valueArray); |
map = makeHash(keyArray, valueArray); |
||
</cfscript></ |
</cfscript></syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<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))</ |
table))</syntaxhighlight> |
||
Or, using cl:loop: |
Or, using cl:loop: |
||
< |
<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 316: | 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)))</ |
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. |
||
=={{header|Crystal}}== |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
<pre> |
|||
{'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26} |
|||
</pre> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
<syntaxhighlight lang="d">void main() { |
|||
<lang d>import std.range: zip; |
|||
import std.array, std.range; |
|||
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray; |
|||
void main() { |
|||
}</syntaxhighlight> |
|||
auto keys = ["one", "two", "three"]; |
|||
auto values = [1, 2, 3]; |
|||
=={{header|Déjà Vu}}== |
|||
int[string] hash; |
|||
<syntaxhighlight 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> |
|||
=={{header|Delphi}}== |
|||
{{libheader| System.SysUtils}} |
|||
{{libheader| System.Generics.Collections}} |
|||
<syntaxhighlight lang="delphi"> |
|||
program Hash_from_two_arrays; |
|||
{$APPTYPE CONSOLE} |
|||
foreach (idx, key; keys) |
|||
hash[key] = values[idx]; |
|||
uses |
|||
// alternative using zip |
|||
System.SysUtils, |
|||
foreach (pair; zip(keys, values)) |
|||
System.Generics.Collections; |
|||
hash[pair[0]] = pair[1]; |
|||
}</lang> |
|||
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}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def keys := ["one", "two", "three"] |
||
def values := [1, 2, 3] |
def values := [1, 2, 3] |
||
__makeMap.fromColumns(keys, values)</ |
__makeMap.fromColumns(keys, values)</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
(lib 'hash) |
|||
(define H (make-hash)) |
|||
(define keys '(elvis simon antoinette)) |
|||
(define kvalues '("the king" "gallubert" "de gabolde d'Audan")) |
|||
(list->hash (map cons keys kvalues) H) |
|||
→ #hash:3 |
|||
(hash-ref H 'elvis) |
|||
→ "the king" |
|||
</syntaxhighlight> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight 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}</syntaxhighlight> |
|||
=={{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|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: hashtables ; |
||
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</ |
{ "one" "two" "three" } { 1 2 3 } zip >hashtable</syntaxhighlight> |
||
=={{header|Falcon}}== |
=={{header|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}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 377: | Line 935: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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. |
|||
<syntaxhighlight lang="frink"> |
|||
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]''' |
|||
<syntaxhighlight 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] |
|||
Dim sCol As New Collection |
|||
Dim siCount As Short |
|||
For siCount = 0 To sKey.max |
|||
sCol.Add(sValue[siCount], sKey[siCount]) |
|||
Next |
|||
For siCount = 0 To sKey.max |
|||
Print Str(sicount) & " = " & sCol[siCount] |
|||
Next |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
0 = Zero |
|||
1 = One |
|||
2 = Two |
|||
3 = Three |
|||
4 = Four |
|||
5 = Five |
|||
</pre> |
|||
=={{header|Go}}== |
=={{header|Go}}== |
||
<syntaxhighlight lang="go">package main |
|||
<lang go>keys := []string{"a", "b", "c"} |
|||
vals := []int{1, 2, 3} |
|||
hash := make(map[string]int) |
|||
import "fmt" |
|||
for i := 0; i < len(keys); i++ { |
|||
hash[keys[i]] = vals[i] |
|||
func main() { |
|||
}</lang> |
|||
keys := []string{"a", "b", "c"} |
|||
vals := []int{1, 2, 3} |
|||
hash := map[string]int{} |
|||
for i, key := range keys { |
|||
hash[key] = vals[i] |
|||
} |
|||
fmt.Println(hash) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
map[b:2 a:1 c:3] |
|||
</pre> |
|||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">def keys = ['a','b','c'] |
||
vals = ['aaa', 'bbb', 'ccc'] |
def vals = ['aaa', 'bbb', 'ccc'] |
||
hash = [:] |
def hash = [:] |
||
keys.eachWithIndex { key, i -> |
keys.eachWithIndex { key, i -> |
||
hash[key] = vals[i] |
hash[key] = vals[i] |
||
}</ |
}</syntaxhighlight> |
||
Alternative Version: |
|||
<syntaxhighlight lang="groovy">List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }</syntaxhighlight> |
|||
Test: |
|||
<syntaxhighlight lang="groovy">assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']</syntaxhighlight> |
|||
=={{header|Harbour}}== |
|||
<syntaxhighlight lang="visualfoxpro">LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 } |
|||
LOCAL hash := { => } |
|||
LOCAL i, j |
|||
FOR EACH i, j IN arr1, arr2 |
|||
hash[ i ] := j |
|||
NEXT</syntaxhighlight> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
{{works with|GHC|GHCi|6.6}} |
{{works with|GHC|GHCi|6.6}} |
||
< |
<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]</ |
mymap = makeMap ['a','b','c'] [1,2,3]</syntaxhighlight> |
||
=={{header|Huginn}}== |
|||
<syntaxhighlight lang="huginn">from Algorithms import materialize, zip; |
|||
main() { |
|||
keys = [1, 2, 3]; |
|||
values = ['a', 'b', 'c']; |
|||
hash = materialize( zip( key, values ), lookup ); |
|||
}</syntaxhighlight> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<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 417: | Line 1,092: | ||
write(ximage(T)) # show result |
write(ximage(T)) # show result |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Ioke}}== |
=={{header|Ioke}}== |
||
< |
<syntaxhighlight lang="ioke">{} addKeysAndValues([:a, :b, :c], [1, 2, 3])</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
What exactly is a hash? |
|||
We shall interpret 'hash' as "a function between some arbitrary values and some other arbitrary values". (Technically speaking a hash is more of a reference to a collection of techniques for achieving this, with something of an emphasis on an arbitrary and opaque intermediate result, than the actual end result. But people have spoken very glowingly of these techniques so let's pretend that the result actually matters.) |
|||
'''Solution:''' |
'''Solution:''' |
||
< |
<syntaxhighlight lang="j">hash=: vals {~ keys&i.</syntaxhighlight> |
||
'''For example:''' |
'''For example:''' |
||
< |
<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 445: | Line 1,124: | ||
six |
six |
||
seven |
seven |
||
two</ |
two</syntaxhighlight> |
||
Here,<code> keys </code>is a list of 10 integers between 0 and 99 chosen |
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}}== |
||
< |
<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 458: | Line 1,137: | ||
hash.put(keys[i], vals[i]); |
hash.put(keys[i], vals[i]); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===Iterative=== |
|||
<lang javascript>var keys = ['a', 'b', 'c']; |
|||
<syntaxhighlight lang="javascript"> |
|||
var keys = ['a', 'b', 'c']; |
|||
var values = [1, 2, 3]; |
var values = [1, 2, 3]; |
||
var map = {}; |
var map = {}; |
||
for(var i |
for(var i = 0; i < keys.length; i += 1) { |
||
map[ keys[i] ] = values[i]; |
map[ keys[i] ] = values[i]; |
||
} |
|||
}</lang> |
|||
</syntaxhighlight> |
|||
===Iterative Using Foreach=== |
|||
<syntaxhighlight lang="javascript"> |
|||
function arrToObj(keys, vals) { |
|||
var map = {}; |
|||
keys.forEach(function (key, index) { |
|||
map[key] = val[index]; |
|||
}); |
|||
return map; |
|||
} |
|||
</syntaxhighlight> |
|||
===Using Reduce=== |
|||
<syntaxhighlight lang="javascript"> |
|||
function arrToObj(keys, vals) { |
|||
return keys.reduce(function(map, key, index) { |
|||
map[key] = vals[index]; |
|||
return map; |
|||
}, {}); |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|jq}}== |
|||
jq only supports hashing of strings. In the following, accordingly, we assume that |
|||
one array (keys) is an array of strings. |
|||
<syntaxhighlight 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. |
|||
# The input array may be of any length and have values of any type, |
|||
# but only the first (keys|length) values will be used; |
|||
# the input will in effect be padded with nulls if required. |
|||
def hash(keys): |
|||
. as $values |
|||
| reduce range(0; keys|length) as $i |
|||
( {}; . + { (keys[$i]) : $values[$i] }); |
|||
[1,2,3] | hash( ["a","b","c"] )</syntaxhighlight> |
|||
{{Out}} |
|||
<syntaxhighlight lang="jq">jq -n -f Hash_from_two_arrays.jq |
|||
{ |
|||
"a": 1, |
|||
"b": 2, |
|||
"c": 3 |
|||
}</syntaxhighlight> |
|||
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:<syntaxhighlight lang="jq">{ |
|||
"1": 10, |
|||
"2": 20, |
|||
"3": 30 |
|||
}</syntaxhighlight> |
|||
=={{header|Jsish}}== |
|||
From Javascript. |
|||
<syntaxhighlight lang="javascript">/* Hash from two arrays, in Jsish */ |
|||
function hashTwo(k:array, v:array):object { |
|||
var hash = {}; |
|||
for (var i = 0; i < k.length; i++) hash[k[i]] = v[i]; |
|||
return hash; |
|||
} |
|||
;hashTwo(['a','b','c'], [1,2,3]); |
|||
;hashTwo(['a','b'], [1,[2,4,8],3]); |
|||
;hashTwo(['a','b','c'], [1,2]); |
|||
;hashTwo([], []); |
|||
/* |
|||
=!EXPECTSTART!= |
|||
hashTwo(['a','b','c'], [1,2,3]) ==> { a:1, b:2, c:3 } |
|||
hashTwo(['a','b'], [1,[2,4,8],3]) ==> { a:1, b:[ 2, 4, 8 ] } |
|||
hashTwo(['a','b','c'], [1,2]) ==> { a:1, b:2, c:undefined } |
|||
hashTwo([], []) ==> {} |
|||
=!EXPECTEND!= |
|||
*/</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ jsish -u hashTwo.jsi |
|||
[PASS] hashTwo.jsi</pre> |
|||
Use '''jsish --U hashTwo.jsi''' to see echo mode test lines. |
|||
=={{header|Julia}}== |
|||
{{works with|Julia|0.6}} |
|||
'''Using comprehension''': |
|||
<syntaxhighlight lang="julia">k = ["a", "b", "c"] |
|||
v = [1, 2, 3] |
|||
Dict(ki => vi for (ki, vi) in zip(k, v))</syntaxhighlight> |
|||
'''Using constructor''': |
|||
<syntaxhighlight lang="julia">Dict(zip(keys, values))</syntaxhighlight> |
|||
'''Specifying types''': |
|||
<syntaxhighlight lang="julia">Dict{String,Int32}(zip(keys, values))</syntaxhighlight> |
|||
=={{header|K}}== |
|||
The keys in a dictionary must be a symbol. |
|||
<syntaxhighlight lang="k"> a: `zero `one `two / symbols |
|||
b: 0 1 2 |
|||
d:. a,'b / create the dictionary |
|||
.((`zero;0;) |
|||
(`one;1;) |
|||
(`two;2;)) |
|||
d[`one] |
|||
1</syntaxhighlight> |
|||
Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols). |
|||
<syntaxhighlight lang="k"> keys: !10 / 0..9 |
|||
split:{1_'(&x=y)_ x:y,x} |
|||
vals:split["zero one two three four five six seven eight nine";" "] |
|||
s:{`$$x} / convert to symbol |
|||
d:. (s'keys),'s'vals |
|||
.((`"0";`zero;) |
|||
(`"1";`one;) |
|||
(`"2";`two;) |
|||
(`"3";`three;) |
|||
(`"4";`four;) |
|||
(`"5";`five;) |
|||
(`"6";`six;) |
|||
(`"7";`seven;) |
|||
(`"8";`eight;) |
|||
(`"9";`nine;)) |
|||
$d[s 1] / leading "$" converts back to string |
|||
"one"</syntaxhighlight> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.1.0 |
|||
fun main(args: Array<String>) { |
|||
val names = arrayOf("Jimmy", "Bill", "Barack", "Donald") |
|||
val ages = arrayOf(92, 70, 55, 70) |
|||
val hash = mapOf(*names.zip(ages).toTypedArray()) |
|||
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") } |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Jimmy aged 92 |
|||
Bill aged 70 |
|||
Barack aged 55 |
|||
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 h, key, value:more(h, {key: value}), |
|||
{:}, 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}}== |
|||
<syntaxhighlight lang="lasso">local( |
|||
array1 = array('a', 'b', 'c'), |
|||
array2 = array(1, 2, 3), |
|||
hash = map |
|||
) |
|||
loop(#array1 -> size) => { |
|||
#hash -> insert(#array1 -> get(loop_count) = #array2 -> get(loop_count)) |
|||
} |
|||
#hash</syntaxhighlight> |
|||
-> map(a = 1, b = 2, c = 3) |
|||
=={{header|LFE}}== |
|||
<syntaxhighlight lang="lisp">(let* ((keys (list 'foo 'bar 'baz)) |
|||
(vals (list '"foo data" '"bar data" '"baz data")) |
|||
(tuples (: lists zipwith |
|||
(lambda (a b) (tuple a b)) keys vals)) |
|||
(my-dict (: dict from_list tuples))) |
|||
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict)))) |
|||
</syntaxhighlight> |
|||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">keys = ["a","b","c"] |
|||
values = [1,2,3] |
|||
props = [:] |
|||
cnt = keys.count |
|||
repeat with i = 1 to cnt |
|||
props[keys[i]] = values[i] |
|||
end repeat |
|||
put props |
|||
-- ["a": 1, "b": 2, "c": 3]</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
|||
<syntaxhighlight lang="livecode">put "a,b,c" into list1 |
|||
put 10,20,30 into list2 |
|||
split list1 using comma |
|||
split list2 using comma |
|||
repeat with i=1 to the number of elements of list1 |
|||
put list2[i] into list3[list1[i]] |
|||
end repeat |
|||
combine list3 using comma and colon |
|||
put list3 |
|||
-- ouput |
|||
-- a:10,b:20,c:30</syntaxhighlight> |
|||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
<syntaxhighlight lang="lua">function(keys,values) |
|||
<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</syntaxhighlight> |
|||
end |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
Module CheckAll { |
|||
Module CheckVectorType { |
|||
Dim Keys$(4), Values(4) |
|||
Keys$(0):= "one","two","three","four" |
|||
Values(0):=1,2,3,4 |
|||
Inventory Dict |
|||
For i=0 to 3 { |
|||
Append Dict, Keys$(i):=Values(i) |
|||
} |
|||
Print Dict("one")+Dict("four")=Dict("two")+Dict("three") ' true |
|||
} |
|||
Module CheckVectorType1 { |
|||
Dim Keys$(4), Values$(4) |
|||
Keys$(0):= "one","two","three","four" |
|||
Values$(0):="*","**","***","****" |
|||
Inventory Dict |
|||
For i=0 to 3 { |
|||
Append Dict, Keys$(i):=Values$(i) |
|||
} |
|||
Print Dict$("one")+Dict$("four")=Dict$("two")+Dict$("three") ' true |
|||
} |
|||
CheckVectorType |
|||
CheckVectorType1 |
|||
} |
|||
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$()) { |
|||
if dimension(a$())<>1 or dimension(b$())<>1 then Error "Only for one dimension arrays" |
|||
if len(a$())<>len(b$()) Then Error "Only for same size arrays" |
|||
start=dimension(a$(),1, 0) |
|||
end=dimension(a$(),1, 1) |
|||
start2=dimension(b$(),1, 0) |
|||
Inventory Hash |
|||
For i=start to end { |
|||
if Exist(hash, a$(i)) Then { |
|||
\\ s is a pointer to a stack object |
|||
s=hash(a$(i)) |
|||
Stack s {Data i-start+start2} |
|||
} Else Append hash, a$(i):=Stack:=i-start+start2 |
|||
} |
|||
=Hash |
|||
} |
|||
Module PrintKeyItems (hash, akey$, &b$()) { |
|||
\\ n=hash(akey$) ' use this if akey$ allways is a proper key |
|||
\\ and hide these two lines using \\ |
|||
if not exist(hash, akey$) then Error "Key not exist" |
|||
n=Eval(hash) |
|||
For i=1 to Len(n) { |
|||
Print b$(stackitem(n,i)), |
|||
} |
|||
Print |
|||
} |
|||
Dim a$(2 to 5) |
|||
Dim b$(4 to 7) |
|||
a$(2)="A", "B","A","C" |
|||
b$(4)="A1","B1","A2", "C1" |
|||
MyHash=MakeHash(&a$(), &b$()) |
|||
PrintkeyItems Myhash, "A", &b$() ' print A1 A2 |
|||
PrintkeyItems Myhash, "B", &b$() ' print B1 |
|||
PrintkeyItems Myhash, "C", &b$() ' print C1 |
|||
} |
|||
Checkit |
|||
</syntaxhighlight> |
|||
=={{header|Maple}}== |
|||
<syntaxhighlight lang="maple">A := [1, 2, 3]; |
|||
B := ["one", "two", three"]; |
|||
T := table( zip( `=`, A, B ) );</syntaxhighlight> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
<syntaxhighlight lang="mathematica">Map[(Hash[Part[#, 1]] = Part[#, 2]) &, |
|||
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]] |
|||
?? Hash |
|||
->Hash[1]=one |
|||
->Hash[2]=two |
|||
->Hash[3]=three</syntaxhighlight> |
|||
=={{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=== |
|||
<syntaxhighlight lang="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 |
|||
% Assumes arrays are same size and valid types |
|||
s = struct; |
|||
if iscell(allVals) |
|||
for k = 1:length(allKeys) |
|||
s.(allKeys{k}) = allVals{k}; |
|||
end |
|||
else |
|||
for k = 1:length(allKeys) |
|||
s.(allKeys{k}) = allVals(k); |
|||
end |
|||
end |
|||
end</syntaxhighlight> |
|||
{{out}} |
|||
<pre>>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27]) |
|||
ages = |
|||
Joe: 21 |
|||
Bob: 35 |
|||
Sue: 27</pre> |
|||
===MATLAB only: containers.Map=== |
|||
containers.Map constructor provides this functionality already. |
|||
<pre>>> ages = containers.Map({'Joe' 'Bob' 'Sue'}, [21 35 27]); |
|||
>> keys(ages) |
|||
ans = |
|||
'Bob' 'Joe' 'Sue' |
|||
>> values(ages) |
|||
ans = |
|||
[35] [21] [27]</pre> |
|||
=={{header|MiniScript}}== |
|||
<syntaxhighlight lang="miniscript">keys = ["foo", "bar", "val"] |
|||
values = ["little", "miss", "muffet"] |
|||
d = {} |
|||
for i in range(keys.len-1) |
|||
d[keys[i]] = values[i] |
|||
end for |
|||
print d</syntaxhighlight> |
|||
{{out}} |
|||
<pre>{"bar": "miss", "foo": "little", "val": "muffet"}</pre> |
|||
=={{header|Neko}}== |
|||
<syntaxhighlight lang="actionscript">/** |
|||
<doc><h2>Hash from two arrays, in Neko</h2></doc> |
|||
**/ |
|||
var sprintf = $loader.loadprim("std@sprintf", 2) |
|||
var array_keys = $array("one",2,"three",4,"five") |
|||
var array_vals = $array("six",7,"eight",9,"zero") |
|||
var elements = $asize(array_keys) |
|||
var table = $hnew(elements) |
|||
var step = elements |
|||
while (step -= 1) >= 0 $hadd(table, $hkey(array_keys[step]), array_vals[step]) |
|||
/* |
|||
$hiter accepts a hashtable and a function that accepts two args, key, val |
|||
*/ |
|||
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n") |
|||
$hiter(table, show)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ nekoc hash-two-arrays.neko |
|||
prompt$ neko hash-two-arrays.n |
|||
Hashed key: 13898426 Value: eight |
|||
Hashed key: 38662 Value: six |
|||
Hashed key: 2 Value: 7 |
|||
Hashed key: 4 Value: 9 |
|||
Hashed key: 737454 Value: zero</pre> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
using Nemerle.Collections; |
using Nemerle.Collections; |
||
Line 495: | Line 1,571: | ||
WriteLine("{0}: {1}", item.Key, item.Value); |
WriteLine("{0}: {1}", item.Key, item.Value); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
|||
=== REXX Style === |
|||
{{trans|REXX}} |
|||
<syntaxhighlight lang="netrexx">/* NetRexx program **************************************************** |
|||
* 04.11.2012 Walter Pachl derived from REXX |
|||
**********************************************************************/ |
|||
options replace format comments java crossref savelog symbols nobinary |
|||
values='triangle quadrilateral pentagon hexagon heptagon octagon' - |
|||
'nonagon decagon dodecagon' |
|||
keys ='three four five six seven eight nine ten twelve' |
|||
kcopy=keys |
|||
k='' /* initialize the arrays */ |
|||
v='' |
|||
value='unknown' |
|||
Loop i=1 By 1 While kcopy>'' /* initialize the two arrays */ |
|||
Parse kcopy ki kcopy; k[i]=ki |
|||
Parse values vi values; v[i]=vi |
|||
End |
|||
Loop j=1 To i-1 |
|||
value[k[j]]=v[j] |
|||
End |
|||
Say 'Enter one of these words:' |
|||
Say ' 'keys |
|||
Parse Ask z |
|||
Say z '->' value[z]</syntaxhighlight> |
|||
=== Java Collections === |
|||
NetRexx has access to Java's Collection objects too. |
|||
<syntaxhighlight lang="netrexx">/* NetRexx */ |
|||
options replace format comments java crossref symbols nobinary |
|||
vals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ] |
|||
keys = [ 'k0', 'k1', 'k2', 'k3', 'k4', 'k5' ] |
|||
hash1 = Rexx |
|||
hash2 = Map |
|||
hash1 = HashMap() |
|||
hash2 = '' |
|||
makeHash(hash1, keys, vals) -- using a Map object (overloaded method) |
|||
makeHash(hash2, keys, vals) -- using a Rexx object (overloaded method) |
|||
return |
|||
-- Using a Java collection object |
|||
method makeHash(hash = Map, keys = Rexx[], vals = Rexx[]) static |
|||
loop k_ = 0 to keys.length - 1 |
|||
hash.put(keys[k_], vals[k_]) |
|||
end k_ |
|||
key = Rexx |
|||
loop key over hash.keySet() |
|||
say key.right(8)':' hash.get(key) |
|||
end key |
|||
say |
|||
return |
|||
-- For good measure a version using the default Rexx object as a hash (associative array) |
|||
method makeHash(hash = Rexx, keys = Rexx[], vals = Rexx[]) static |
|||
loop k_ = 0 to keys.length - 1 |
|||
hash[keys[k_]] = vals[k_] |
|||
end k_ |
|||
loop key over hash |
|||
say key.right(8)':' hash[key] |
|||
end key |
|||
say |
|||
return |
|||
</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">import tables, sequtils |
|||
let keys = @['a','b','c'] |
|||
let values = @[1, 2, 3] |
|||
let table = toTable zip(keys, values)</syntaxhighlight> |
|||
=={{header|Oberon-2}}== |
|||
Works with oo2c version 2 |
|||
<syntaxhighlight lang="oberon2"> |
|||
MODULE HashFromArrays; |
|||
IMPORT |
|||
ADT:Dictionary, |
|||
Object:Boxed; |
|||
TYPE |
|||
Key= STRING; |
|||
Value= Boxed.LongInt; |
|||
PROCEDURE Do; |
|||
VAR |
|||
a: ARRAY 128 OF Key; |
|||
b: ARRAY 128 OF Value; |
|||
hash: Dictionary.Dictionary(Key,Value); |
|||
i: INTEGER; |
|||
BEGIN |
|||
hash := NEW(Dictionary.Dictionary(Key,Value)); |
|||
a[0] := "uno"; |
|||
a[1] := "dos"; |
|||
a[2] := "tres"; |
|||
a[3] := "cuatro"; |
|||
b[0] := Boxed.ParseLongInt("1"); |
|||
b[1] := Boxed.ParseLongInt("2"); |
|||
b[2] := Boxed.ParseLongInt("3"); |
|||
b[3] := Boxed.ParseLongInt("4"); |
|||
i := 0; |
|||
WHILE (i < LEN(a)) & (a[i] # NIL) DO |
|||
hash.Set(a[i],b[i]); |
|||
INC(i) |
|||
END; |
|||
END Do; |
|||
BEGIN |
|||
Do; |
|||
END HashFromArrays. |
|||
</syntaxhighlight> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
use Structure; |
use Structure; |
||
Line 514: | Line 1,709: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
< |
<syntaxhighlight lang="objc">NSArray *keys = @[@"a", @"b", @"c"]; |
||
NSArray *values = [ |
NSArray *values = @[@1, @2, @3]; |
||
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</syntaxhighlight> |
|||
[NSNumber numberWithInt:2], |
|||
[NSNumber numberWithInt:3], nil]; |
|||
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];</lang> |
|||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
The idiomatic solution uses lists rather than arrays. |
The idiomatic solution uses lists rather than arrays. |
||
< |
<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;;</ |
List.iter2 (Hashtbl.add hash) keys vals;;</syntaxhighlight> |
||
The solution is similar with arrays. |
|||
In the extremely unlikely event that it was actually necessary to use arrays, the solution would become slightly less elegant: |
|||
(except using the ExtLib which provides the equivalent Array.iter2) |
|||
< |
<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;;</syntaxhighlight> |
|||
for i = 0 to Array.length keys - 1 do |
|||
Hashtbl.add hash keys.(i) vals.(i) |
|||
done;;</lang> |
|||
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 548: | Line 1,738: | ||
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: |
||
< |
<syntaxhighlight lang="ocaml">module StringMap = Map.Make (String);; |
||
let keys = [ "foo"; "bar"; "baz" ] |
let keys = [ "foo"; "bar"; "baz" ] |
||
Line 554: | Line 1,744: | ||
and map = StringMap.empty;; |
and map = StringMap.empty;; |
||
let map = List.fold_right2 StringMap.add keys vals map;;</ |
let map = List.fold_right2 StringMap.add keys vals map;;</syntaxhighlight> |
||
=={{header|ooRexx}}== |
|||
<syntaxhighlight lang="oorexx">array1 = .array~of("Rick", "Mike", "David") |
|||
array2 = .array~of("555-9862", "555-5309", "555-6666") |
|||
-- if the index items are constrained to string objects, this can |
|||
-- be a directory too. |
|||
hash = .table~new |
|||
loop i = 1 to array1~size |
|||
hash[array1[i]] = array2[i] |
|||
end |
|||
Say 'Enter a name' |
|||
Parse Pull name |
|||
Say name '->' hash[name]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>Enter a name |
|||
Rick |
|||
Rick -> 555-9862</pre> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<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 566: | Line 1,775: | ||
end |
end |
||
in |
in |
||
{Show {ZipRecord [a b c] [1 2 3]}}</ |
{Show {ZipRecord [a b c] [1 2 3]}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
|||
<syntaxhighlight lang="parigp">hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));</syntaxhighlight> |
|||
=={{header|Pascal}}== |
|||
{{works with|Free_Pascal}} |
|||
{{libheader|contnrs}} |
|||
<syntaxhighlight lang="pascal">program HashFromTwoArrays (Output); |
|||
uses |
|||
contnrs; |
|||
var |
|||
keys: array[1..3] of string = ('a', 'b', 'c'); |
|||
values: array[1..3] of integer = ( 1, 2, 3 ); |
|||
hash: TFPDataHashTable; |
|||
i: integer; |
|||
begin |
|||
hash := TFPDataHashTable.Create; |
|||
for i := low(keys) to high(keys) do |
|||
hash.add(keys[i], @values[i]); |
|||
writeln ('Length of hash table: ', hash.Count); |
|||
hash.Destroy; |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
<pre>% ./HashFromTwoArrays |
|||
Length of hash table: 3 |
|||
</pre> |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
begin |
|||
var Keys := Arr('aa','bb','cc'); |
|||
var Values := Arr(1..3); |
|||
var dct := Dict(Keys.Zip(Values)); |
|||
dct.Println; |
|||
end. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
(aa,1) (bb,2) (cc,3) |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<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;</ |
@hash{@keys} = @vals;</syntaxhighlight> |
||
Alternatively, using {{libheader|List::MoreUtils}}: |
Alternatively, using {{libheader|List::MoreUtils}}: |
||
< |
<syntaxhighlight lang="perl">use List::MoreUtils qw(zip); |
||
my %hash = zip @keys, @vals;</ |
my %hash = zip @keys, @vals;</syntaxhighlight> |
||
=={{header| |
=={{header|Phix}}== |
||
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out. |
|||
{{works with|Rakudo|#23 "Lisbon"}} |
|||
<!--<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> |
|||
"one" |
|||
2 |
|||
3.141592654 |
|||
</pre> |
|||
=={{header|Phixmonti}}== |
|||
<lang perl6>my @keys = <a b c d e>; |
|||
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt |
|||
my @vals = ^5; |
|||
my %hash = @keys Z @vals;</lang> |
|||
def getd /# array key -- array data #/ |
|||
Alternatively: |
|||
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 #/ |
|||
<lang perl6>my %hash; |
|||
%hash{@keys} = @vals;</lang> |
|||
1 getd print nl |
|||
To create an anonymous hash value, you can use Z as a "zipwith" metaoperator on the => pair composer: |
|||
"two" getd print nl |
|||
PI getd tostr print nl |
|||
<lang perl6>{ <a b c d e> Z=> ^5 }</lang> |
|||
3 getd print</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
one |
|||
2 |
|||
3.141592653589793 |
|||
Unfound |
|||
</pre> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
{{works with|PHP|5}} |
{{works with|PHP|5}} |
||
< |
<syntaxhighlight lang="php">$keys = array('a', 'b', 'c'); |
||
$values = array(1, 2, 3); |
$values = array(1, 2, 3); |
||
$hash = array_combine($keys, $values);</ |
$hash = array_combine($keys, $values);</syntaxhighlight> |
||
{{works with|PHP|4}} |
{{works with|PHP|4}} |
||
< |
<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]; |
||
}</ |
}</syntaxhighlight> |
||
=={{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}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(let (Keys '(one two three) Values (1 2 3)) |
||
(mapc println |
(mapc println |
||
(mapcar cons Keys Values) ) )</ |
(mapcar cons Keys Values) ) )</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>(one . 1) |
<pre>(one . 1) |
||
(two . 2) |
(two . 2) |
||
(three . 3)</pre> |
(three . 3)</pre> |
||
=={{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> |
|||
([ /* 3 elements */ |
|||
"a": Image.Color.black, |
|||
"b": "hello" |
|||
42: "world", |
|||
]) |
|||
</pre> |
|||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<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 628: | Line 1,947: | ||
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;</ |
endfor;</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
{{libheader|initlib}} |
{{libheader|initlib}} |
||
< |
<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 639: | Line 1,958: | ||
% show that we have created the hash |
% show that we have created the hash |
||
{= =} forall |
{= =} forall |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<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 653: | Line 1,973: | ||
} |
} |
||
return $h |
return $h |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">% this one with side effect hash table creation |
||
:-dynamic hash/2. |
:-dynamic hash/2. |
||
Line 675: | Line 1,995: | ||
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).</ |
:-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}}== |
||
< |
<syntaxhighlight lang="purebasic">Dim keys.s(3) |
||
Dim vals.s(3) |
Dim vals.s(3) |
||
NewMap Hash.s() |
NewMap Hash.s() |
||
Line 689: | Line 2,009: | ||
ForEach Hash() |
ForEach Hash() |
||
Debug Hash() |
Debug Hash() |
||
Next</ |
Next</syntaxhighlight> |
||
=={{header|Python}}== |
=={{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): |
|||
<syntaxhighlight lang="python">keys = ['a', 'b', 'c'] |
|||
values = [1, 2, 3] |
|||
hash = {key: value for key, value in zip(keys, values)}</syntaxhighlight> |
|||
{{works with|Python|2.2+}} |
{{works with|Python|2.2+}} |
||
< |
<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 699: | Line 2,025: | ||
# 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))</ |
hash = dict(izip(keys, values))</syntaxhighlight> |
||
{{works with|Python|3.0+}} |
|||
Shows off the dict comprehensions in Python 3: |
|||
<lang python>keys = ['a', 'b', 'c'] |
|||
values = [1, 2, 3] |
|||
hash = {key: value for key, value in zip(keys, values)}</lang> |
|||
{{works with|Python|2.0+}} |
{{works with|Python|2.0+}} |
||
< |
<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</ |
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): |
||
< |
<syntaxhighlight lang="python">>>> class Hashable(object): |
||
def __hash__(self): |
def __hash__(self): |
||
return id(self) ^ 0xBEEF |
return id(self) ^ 0xBEEF |
||
Line 755: | Line 2,075: | ||
<__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</ |
>>> # 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]]. |
||
< |
<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 766: | Line 2,086: | ||
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"</ |
names(values)[values==152] # "John Smith" "Sandra Dee"</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang scheme>(make-hash |
|||
(make-hash (map cons '("a" "b" "c" "d") '(1 2 3 4)))</syntaxhighlight> |
|||
(map cons |
|||
'("a" "b" "c" "d") |
|||
Alternatively: |
|||
'(1 2 3 4)))</lang> |
|||
<syntaxhighlight 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> |
|||
=={{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}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang="raven">[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals |
||
$keys $vals combine as $hash</ |
$keys $vals combine as $hash</syntaxhighlight> |
||
=={{header|REXX}}== |
|||
This REXX version allows multiple keys for a value, the keys are case sensitive. |
|||
<syntaxhighlight 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' |
|||
key.1='thuhree vour phive sicks zeaven ate nein den duzun' |
|||
key.2='three four five six seven eight nine ten twelve' |
|||
key.3='3 4 5 6 7 8 9 10 12' |
|||
key.4='III IV V VI VII VIII IX X XII' |
|||
key.5='iii iv v vi vii viii ix x xii' |
|||
hash.='───(not defined)───' /* [↑] blanks added to humorous keys */ |
|||
/* just because it looks prettier.*/ |
|||
do k=1 while key.k\=='' |
|||
call hash vals,key.k /*hash the keys to the values. */ |
|||
end /*k*/ |
|||
parse arg query . /*obtain what was specified on the C.L.*/ |
|||
if query\=='' then say 'key:' left(query,40) "value:" hash.query |
|||
exit /*stick a fork in it, we're all done. */ |
|||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
|||
hash: parse arg @val,@key |
|||
do j=1 for words(@key); map= word(@key, j) |
|||
hash.map= word(@val, j) |
|||
end /*j*/ |
|||
return</syntaxhighlight> |
|||
{{out|output|text= when using the input value of: <tt> phive </tt>}} |
|||
<pre> |
|||
key: phive value: pentagon |
|||
</pre> |
|||
{{out|output|text= when using the input value of: <tt> dingsta </tt>}} |
|||
<pre> |
|||
key: dingsta value: ───(not defined)─── |
|||
</pre> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
# Project : Hash from two arrays |
|||
list1="one two three" |
|||
list2="1 2 3" |
|||
a = str2list(substr(list1," ",nl)) |
|||
b = str2list(substr(list2," ",nl)) |
|||
c = list(len(a)) |
|||
for i=1 to len(b) |
|||
temp = number(b[i]) |
|||
c[temp] = a[i] |
|||
next |
|||
for i = 1 to len(c) |
|||
see c[i] + " " + i + nl |
|||
next |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
one 1 |
|||
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}}== |
=={{header|Ruby}}== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang ruby>keys=['hal',666,[1,2,3]] |
|||
keys = ['hal',666,[1,2,3]] |
|||
vals = ['ibm','devil',123] |
|||
hash = Hash[keys.zip(vals)] |
|||
if RUBY_VERSION >= '1.8.7' |
|||
# Easy way, but needs Ruby 1.8.7 or later. |
|||
hash = Hash[keys.zip(vals)] |
|||
else |
|||
hash = {} |
|||
keys.each_index {|i| hash.store keys[i], vals[i] } |
|||
end |
|||
p hash # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123} |
p hash # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123} |
||
#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> |
|||
In Ruby 2.1 the method "to_h" was introduced: |
|||
<syntaxhighlight lang="ruby">keys = ['hal', 666, [1,2,3]] |
|||
vals = ['ibm', 'devil', 123] |
|||
keys.zip(vals).to_h</syntaxhighlight> |
|||
<lang ruby>class Array |
|||
def zip_hash(other) |
|||
=={{header|Rust}}== |
|||
Hash[*(0...self.size).inject([]) { |arr, ix| |
|||
<syntaxhighlight lang="rust">use std::collections::HashMap; |
|||
arr.push(self[ix], other[ix]) } ] |
|||
end |
|||
end |
|||
fn main() { |
|||
hash = %W{ a b c }.zip_hash( %W{ 1 2 3 } ) |
|||
let keys = ["a", "b", "c"]; |
|||
let values = [1, 2, 3]; |
|||
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>(); |
|||
Reference from [http://programmingbulls.com/ruby-array-hash Ruby Array to Hash] |
|||
println!("{:?}", hash); |
|||
}</syntaxhighlight> |
|||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<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 833: | Line 2,258: | ||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">val keys = List(1, 2, 3) |
||
val values = Array("A", "B", "C") |
val values = Array("A", "B", "C") // Array mixed with List |
||
val map = |
val map = keys.zip(values).toMap // and other Seq are possible. |
||
// returns Map(1 -> "A", 2 -> "B", 3 -> "C") |
|||
// Testing |
|||
// keys.zip(values) is an array of pairs : Array((1, "A"), (2, "B"), (3, "C")) |
|||
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C")) |
|||
// Map(...) expects multiple pairs arguments. Syntax ": _*" tells the single argument contains multiple values.</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] === |
||
< |
<syntaxhighlight lang="scheme">(define (lists->hash-table keys values . rest) |
||
(apply alist->hash-table (map cons keys values) rest))</ |
(apply alist->hash-table (map cons keys values) rest))</syntaxhighlight> |
||
=== 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}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const type: numericHash is hash [string] integer; |
const type: numericHash is hash [string] integer; |
||
Line 864: | Line 2,353: | ||
myHash @:= [keyList[number]] valueList[number]; |
myHash @:= [keyList[number]] valueList[number]; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
|||
<syntaxhighlight lang="sensetalk"> |
|||
set keyList to ["red", "green", "blue"] |
|||
set valueList to [150,0,128] |
|||
repeat with n=1 to the number of items in keyList |
|||
set map.(item n of keyList) to item n of valueList |
|||
end repeat |
|||
put map |
|||
--> (blue:"128", green:"0", red:"150") |
|||
</syntaxhighlight> |
|||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby">var keys = %w(a b c) |
|||
var vals = [1, 2, 3] |
|||
var hash = Hash() |
|||
hash{keys...} = vals... |
|||
say hash</syntaxhighlight> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">Array extend [ |
||
dictionaryWithValues: array [ |d| |
dictionaryWithValues: array [ |d| |
||
d := Dictionary new. |
d := Dictionary new. |
||
Line 881: | Line 2,392: | ||
({ 'red' . 'one' . 'two' } |
({ 'red' . 'one' . 'two' } |
||
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</ |
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.</syntaxhighlight> |
||
{{works with|Smalltalk/X}} |
|||
{{works with|VisualWorks Smalltalk}} |
|||
<syntaxhighlight lang="smalltalk">Dictionary |
|||
withKeys:#('one' 'two' 'three') |
|||
andValues:#('eins' 'zwei' 'drei')</syntaxhighlight> |
|||
{{works with|Smalltalk/X}} |
|||
<syntaxhighlight lang="smalltalk">Dictionary withAssociations:{ 'one'->1 . 'two'->2 . 'three'->3 }</syntaxhighlight> |
|||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 889: | Line 2,409: | ||
{{works with|CSnobol}} |
{{works with|CSnobol}} |
||
< |
<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 904: | Line 2,424: | ||
str = str ch ':' hash<ch> ' ' :(tloop) |
str = str ch ':' hash<ch> ' ' :(tloop) |
||
out output = str |
out output = str |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
|||
Output: |
|||
<pre>A:1 B:2 C:3 D:4 E:5</pre> |
<pre>A:1 B:2 C:3 D:4 E:5</pre> |
||
=={{header|Sparkling}}== |
|||
<syntaxhighlight 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]; |
|||
}</syntaxhighlight> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
Line 913: | Line 2,441: | ||
Using functional binary search trees instead of hash tables: |
Using functional binary search trees instead of hash tables: |
||
< |
<syntaxhighlight lang="sml">structure StringMap = BinaryMapFn (struct |
||
type ord_key = string |
type ord_key = string |
||
val compare = String.compare |
val compare = String.compare |
||
Line 922: | Line 2,450: | ||
and myMap = StringMap.empty; |
and myMap = StringMap.empty; |
||
val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));</ |
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: |
||
< |
<syntaxhighlight lang="sml">exception NotFound; |
||
val keys = [ "foo", "bar", "baz" ] |
val keys = [ "foo", "bar", "baz" ] |
||
Line 933: | Line 2,461: | ||
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);</ |
ListPair.appEq (HashTable.insert hash) (keys, vals);</syntaxhighlight> |
||
=={{header|Swift}}== |
|||
{{works with|Swift|1.2+}} |
|||
<syntaxhighlight 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 |
|||
}</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Arrays in Tcl are automatically associative, |
Arrays in Tcl are automatically associative, |
||
i.e. there are no "not hashed arrays". <br> |
|||
<lang tcl>set keys [list fred bob joe] |
|||
If we can take "arrays of equal length" to mean |
|||
"<i>lists</i> of equal length", |
|||
then the task might look like this: |
|||
<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 } |
||
Alternatively, a dictionary could be used: |
|||
parray arr</syntaxhighlight> |
|||
<lang tcl>foreach a $keys b $values { |
|||
{{out}} |
|||
<pre> |
|||
arr(bob) = plumber |
|||
arr(fred) = barber |
|||
arr(joe) = tailor |
|||
</pre> |
|||
Alternatively, a dictionary could be used: <!-- http://ideone.com/6lI4k5 --> |
|||
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
|||
set keys [list fred bob joe] |
|||
set values [list barber plumber tailor] |
|||
foreach a $keys b $values { |
|||
dict set jobs $a $b |
dict set jobs $a $b |
||
} |
|||
}</lang> |
|||
puts "jobs: [dict get $jobs]"</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
jobs: fred barber bob plumber joe tailor |
|||
</pre> |
|||
=={{header|TXR}}== |
|||
===One-liner, using quasiquoted hash syntax=== |
|||
<syntaxhighlight lang="bash">$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))' |
|||
#H(() (c 3) (b 2) (a 1))</syntaxhighlight> |
|||
===One-liner, using <code>hash-construct</code> function=== |
|||
<syntaxhighlight lang="bash">$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))' |
|||
#H(() (c 3) (b 2) (a 1))</syntaxhighlight> |
|||
===Explicit construction and stuffing=== |
|||
<syntaxhighlight 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)))</syntaxhighlight> |
|||
<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}}== |
=={{header|UnixPipes}}== |
||
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.) |
||
< |
<syntaxhighlight lang="bash">cat <<VAL >p.values |
||
apple |
apple |
||
boy |
boy |
||
Line 966: | Line 2,570: | ||
KEYS |
KEYS |
||
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</ |
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
There |
There is a built-in operator for this. |
||
< |
<syntaxhighlight lang="ursala">keys = <'foo','bar','baz'> |
||
values = <12354,145430,76748> |
values = <12354,145430,76748> |
||
hash_function = keys-$values</ |
hash_function = keys-$values</syntaxhighlight> |
||
test program: |
test program: |
||
< |
<syntaxhighlight lang="ursala">#cast %nL |
||
test = hash_function* <'bar','baz','foo','bar'></ |
test = hash_function* <'bar','baz','foo','bar'></syntaxhighlight> |
||
{{out}} |
|||
output: |
|||
<pre><145430,76748,12354,145430></pre> |
<pre><145430,76748,12354,145430></pre> |
||
=={{header|Vala}}== |
|||
{{libheader|Gee}} |
|||
<syntaxhighlight lang="vala"> |
|||
using Gee; |
|||
void main(){ |
|||
// mostly copied from C# example |
|||
var hashmap = new HashMap<string, string>(); |
|||
string[] arg_keys = {"foo", "bar", "val"}; |
|||
string[] arg_values = {"little", "miss", "muffet"}; |
|||
if (arg_keys.length == arg_values.length ){ |
|||
for (int i = 0; i < arg_keys.length; i++){ |
|||
hashmap[arg_keys[i]] = arg_values[i]; |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
Line 985: | Line 2,609: | ||
VBScript (and Visual Basic in general) calls hashes "dictionary objects". |
VBScript (and Visual Basic in general) calls hashes "dictionary objects". |
||
< |
<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 993: | Line 2,617: | ||
MsgBox dict.Item("Linux") |
MsgBox dict.Item("Linux") |
||
MsgBox dict.Item("MacOS") |
MsgBox dict.Item("MacOS") |
||
MsgBox dict.Item("Windows")</ |
MsgBox dict.Item("Windows")</syntaxhighlight> |
||
Output (in message boxes): |
|||
{{out}} (in message boxes): |
|||
Linus Torvalds |
Linus Torvalds |
||
Apple |
Apple |
||
Line 1,004: | Line 2,627: | ||
{{trans|VBScript}} |
{{trans|VBScript}} |
||
The [[Hash from two arrays#VBScript|VBScript]] version can be used |
The [[Hash from two arrays#VBScript|VBScript]] version can be used |
||
in Visual Basic unchanged, although it requires a reference to |
|||
the [[Windows Script Host|Microsoft Scripting Runtime (scrrun.dll)]]. |
|||
Alternately, instead of a <code>Dictionary</code> object, |
|||
Alternately, instead of a <code>Dictionary</code> object, you can also use a <code>Collection</code> object, which serves a similar purpose, without the inclusion of an additional runtime library. In fact, the only immediately-obvious difference between this and the VBScript example is <code>dict</code>'s data type, and the order that the arguments are passed to the <code>Add</code> method. |
|||
you can also use a <code>Collection</code> object, |
|||
which serves a similar purpose, without the inclusion |
|||
of an additional runtime library. |
|||
In fact, the only immediately-obvious difference between this |
|||
and the VBScript example is <code>dict</code>'s data type, |
|||
and the order that the arguments are passed to the <code>Add</code> method. |
|||
< |
<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 1,016: | Line 2,647: | ||
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")</ |
Debug.Print dict.Item("Windows")</syntaxhighlight> |
||
=={{header|WDTE}}== |
|||
<syntaxhighlight lang="wdte">let a => import 'arrays'; |
|||
let s => import 'stream'; |
|||
let toScope keys vals => |
|||
s.zip (a.stream keys) (a.stream vals) |
|||
-> |
|||
s.reduce (collect (true)) (@ r scope kv => |
|||
let [k v] => kv; |
|||
set scope k v; |
|||
) |
|||
;</syntaxhighlight> |
|||
'''Example:''' |
|||
<syntaxhighlight lang="wdte">toScope |
|||
['a'; 'b'; 'c'] |
|||
[1; 2; 3] |
|||
: scope |
|||
-> known |
|||
-> a.stream |
|||
-> s.map (@ m k => [k; at scope k]) |
|||
-> s.collect |
|||
-- io.writeln io.stdout |
|||
;</syntaxhighlight> |
|||
{{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>. |
|||
<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: |
|||
<syntaxhighlight lang="wortel">^(@obj @zip)</syntaxhighlight> |
|||
Example: |
|||
<syntaxhighlight lang="wortel">@let { |
|||
hash ^(@obj @zip) |
|||
!!hash ["a" "b" "c"] [1 2 3] |
|||
}</syntaxhighlight> |
|||
{{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}}== |
|||
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} {{omit from|PowerBASIC}} {{omit from|BASIC}} <!-- Does not have hash tables or other map structures. --> |
|||
<syntaxhighlight lang="zkl">keys:=T("a","b","c","d"); vals:=T(1,2,3,4); |
|||
d:=keys.zip(vals).toDictionary(); |
|||
d.println(); |
|||
d["b"].println();</syntaxhighlight> |
|||
{{out}} |
|||
<pre>D(a:1,b:2,c:3,d:4) |
|||
2 |
|||
</pre> |
Latest revision as of 14:42, 23 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values)
- Related task
11l
V keys = [‘a’, ‘b’, ‘c’]
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
print(hash_)
ActionScript
package
{
public class MyClass
{
public static function main():Void
{
var hash:Object = new Object();
var keys:Array = new Array("a", "b", "c");
var values:Array = new Array(1, 2, 3);
for (var i:int = 0; i < keys.length(); i++)
hash[keys[i]] = values[i];
}
}
}
Ada
with Ada.Strings.Hash;
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Hash_Map_Test is
function Equivalent_Key (Left, Right : Unbounded_String) return Boolean is
begin
return Left = Right;
end Equivalent_Key;
function Hash_Func(Key : Unbounded_String) return Ada.Containers.Hash_Type is
begin
return Ada.Strings.Hash(To_String(Key));
end Hash_Func;
package My_Hash is new Ada.Containers.Hashed_Maps(Key_Type => Unbounded_String,
Element_Type => Unbounded_String,
Hash => Hash_Func,
Equivalent_Keys => Equivalent_Key);
type String_Array is array(Positive range <>) of Unbounded_String;
Hash : My_Hash.Map;
Key_List : String_Array := (To_Unbounded_String("foo"),
To_Unbounded_String("bar"),
To_Unbounded_String("val"));
Element_List : String_Array := (To_Unbounded_String("little"),
To_Unbounded_String("miss"),
To_Unbounded_String("muffet"));
begin
for I in Key_List'range loop
Hash.Insert(Key => (Key_List(I)),
New_Item => (Element_List(I)));
end loop;
for I in Key_List'range loop
Ada.Text_Io.Put_Line(To_String(Key_List(I)) & " => " &
To_String(Hash.Element(Key_List(I))));
end loop;
end Hash_Map_Test;
Amazing Hopper
Example:
#!/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)
Output:
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
Macros used in the example, located in "hopper.h". (Observation: some of these macros will be converted to libraries, due to their extension.)
/* 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
Argile
use std, array, hash
let keys = @["hexadecimal" "decimal" "octal" "binary"]
let values = @[0xa 11 014 0b1101] (: 10 11 12 13 :)
let hash = new hash of int
for each val int i from 0 to 3
hash[keys[i]] = values[i]
del hash hash
Arturo
h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h
- Output:
[a:1 b:2 c:3 d:4]
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"]
AWK
Awk arrays are used for both lists and hash maps.
# usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk
BEGIN {
if(!list1) list1="one two three"
if(!list2) list2="1 2 3"
split(list1, a);
split(list2, b);
for(i=1;i in a;i++) { c[a[i]] = b[i] };
for(i in c) print i,c[i]
}
- Output:
three 3 two 2 one 1
BASIC256
Solution is at Associative_array/Creation#BASIC256.
BBC BASIC
DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
FOR index% = 0 TO DIM(array1$(),1)
PROCputdict(mydict$, array2$(index%), array1$(index%))
NEXT
PRINT FNgetdict(mydict$, "3")
END
DEF PROCputdict(RETURN dict$, value$, key$)
IF dict$ = "" dict$ = CHR$(0)
dict$ += key$ + CHR$(1) + value$ + CHR$(0)
ENDPROC
DEF FNgetdict(dict$, key$)
LOCAL I%, J%
I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1))
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)
Bracmat
two three apple:?arr1
& 2 3 fruit:?arr2
& new$hash:?H
& whl
' ( !arr1:%?k ?arr1
& !arr2:%?v ?arr2
& (H..insert)$(!k.!v)
)
& (H..forall)$out
& ;
- Output:
apple.fruit three.3 two.2
Brat
zip = { keys, values |
h = [:]
keys.each_with_index { key, index |
h[key] = values[index]
}
h
}
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]
C
There likely exist libraries that can be used for creating hashes that are better than the following implementation. There are also better functions for obtaining hash values from strings. The following implementation tries to be somewhat generic to facilitate using alternative key and value types.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
// hash function useful when KeyType is char * (string)
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
// printf("Dup. hash key\n");
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, ©Str, ©Int, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
}
C#
C# 1.0
static class Program
{
static void Main()
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for (int i = 0; i < keys.Length; i++)
{
h.Add(keys[i], values[i]);
}
}
}
Hashtable.Add
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:
h[keys[i]] = values[i];
Modern
Uses System.Collections.Generic.Dictionary<TKey, TValue>
, Enumerable.ToDictionary
from LINQ, extension method syntax, and lambda expressions.
Enumerable.Zip
truncates the longer of its arguments.
using System.Linq;
static class Program
{
static void Main()
{
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
var h = keys
.Zip(values, (k, v) => (k, v))
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}
C++
#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] ;
}
#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));
}
Ceylon
shared void run() {
value keys = [1, 2, 3];
value items = ['a', 'b', 'c'];
value hash = map(zipEntries(keys, items));
}
Clojure
(zipmap [\a \b \c] [1 2 3])
Coco
keys = <[apple banana orange grape]>
values = <[red yellow orange purple]>
object = new
@[keys[i]] = values[i] for i til keys.length
CoffeeScript
keys = ['a','b','c']
values = [1,2,3]
map = {}
map[key] = values[i] for key, i in keys
ColdFusion
<cfscript>
function makeHash(keyArray, valueArray) {
var x = 1;
var result = {};
for( ; x <= ArrayLen(keyArray); x ++ ) {
result[keyArray[x]] = valueArray[x];
}
return result;
}
keyArray = ['a', 'b', 'c'];
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
</cfscript>
Common 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))
Or, using cl:loop:
(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))
for k across vector-1
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.
Crystal
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
{'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26}
D
void main() {
import std.array, std.range;
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}
Déjà Vu
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
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.
- Output:
b 2 a 1 c 3
Diego
Diego has in-built hash
and dict
(short for 'dictionary') objects which function the same, except hash
can only accept uuid datatypes for keys. Diego also has hash_
verb and _hash
posit, used to hash an object/command.
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[];
Arrays can manually be mapped from two arrays using a _for
posit, for instance:
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[];
E
def keys := ["one", "two", "three"]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)
EchoLisp
(lib 'hash)
(define H (make-hash))
(define keys '(elvis simon antoinette))
(define kvalues '("the king" "gallubert" "de gabolde d'Audan"))
(list->hash (map cons keys kvalues) H)
→ #hash:3
(hash-ref H 'elvis)
→ "the king"
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}
Emacs 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))))
EMal
List keys = var["hal", 666, int[1,2,3]]
List vals = var["ibm", "devil", 123]
Map hash = keys.zip(vals)
writeLine(hash)
- Output:
[hal:ibm,666:devil,[1,2,3]:123]
Erlang
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).
F#
HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)
Factor
USING: hashtables ;
{ "one" "two" "three" } { 1 2 3 } zip >hashtable
Falcon
keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]
Fantom
class Main
{
public static Void main ()
{
keys := [1,2,3,4,5]
values := ["one", "two", "three", "four", "five"]
// create an empty map
map := [:]
// add the key-value pairs to it
keys.size.times |Int index|
{
map.add(keys[index], values[index])
}
}
}
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
- Output:
1 one 2 two 3 three 4 four 5 five
Frink
There is a built-in dictionary/hash constructor that takes two arrays as input.
a = new dict[["a", "b", "c"], [1, 2, 3]]
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
- Output:
{ Key1 = One; Key2 = Two; Key3 = Three; Key4 = "O'Leary"; }
Gambas
Click this link to run this code
Public Sub Main()
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Dim sCol As New Collection
Dim siCount As Short
For siCount = 0 To sKey.max
sCol.Add(sValue[siCount], sKey[siCount])
Next
For siCount = 0 To sKey.max
Print Str(sicount) & " = " & sCol[siCount]
Next
End
Output:
0 = Zero 1 = One 2 = Two 3 = Three 4 = Four 5 = Five
Go
package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}
- Output:
map[b:2 a:1 c:3]
Groovy
def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
}
Alternative Version:
List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }
Test:
assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']
Harbour
LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
LOCAL hash := { => }
LOCAL i, j
FOR EACH i, j IN arr1, arr2
hash[ i ] := j
NEXT
Haskell
import Data.Map
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]
Huginn
from Algorithms import materialize, zip;
main() {
keys = [1, 2, 3];
values = ['a', 'b', 'c'];
hash = materialize( zip( key, values ), lookup );
}
Icon and Unicon
Ioke
{} addKeysAndValues([:a, :b, :c], [1, 2, 3])
J
What exactly is a hash?
We shall interpret 'hash' as "a function between some arbitrary values and some other arbitrary values". (Technically speaking a hash is more of a reference to a collection of techniques for achieving this, with something of an emphasis on an arbitrary and opaque intermediate result, than the actual end result. But people have spoken very glowingly of these techniques so let's pretend that the result actually matters.)
Solution:
hash=: vals {~ keys&i.
For example:
keys=: 10?.100
vals=: > ;:'zero one two three four five six seven eight nine'
hash=: vals {~ keys&i.
keys
46 99 23 62 42 44 12 5 68 63
$vals
10 5
hash 46
zero
hash 99
one
hash 63 5 12 5 23
nine
seven
six
seven
two
Here, keys
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 vals
is a 10 by 5 character matrix.
Java
import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}
JavaScript
Iterative
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i = 0; i < keys.length; i += 1) {
map[ keys[i] ] = values[i];
}
Iterative Using Foreach
function arrToObj(keys, vals) {
var map = {};
keys.forEach(function (key, index) {
map[key] = val[index];
});
return map;
}
Using Reduce
function arrToObj(keys, vals) {
return keys.reduce(function(map, key, index) {
map[key] = vals[index];
return map;
}, {});
}
jq
jq only supports hashing of strings. In the following, accordingly, we assume that one array (keys) is an array of strings.
# 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.
# The input array may be of any length and have values of any type,
# but only the first (keys|length) values will be used;
# the input will in effect be padded with nulls if required.
def hash(keys):
. as $values
| reduce range(0; keys|length) as $i
( {}; . + { (keys[$i]) : $values[$i] });
[1,2,3] | hash( ["a","b","c"] )
- Output:
jq -n -f Hash_from_two_arrays.jq
{
"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
}
Jsish
From Javascript.
/* Hash from two arrays, in Jsish */
function hashTwo(k:array, v:array):object {
var hash = {};
for (var i = 0; i < k.length; i++) hash[k[i]] = v[i];
return hash;
}
;hashTwo(['a','b','c'], [1,2,3]);
;hashTwo(['a','b'], [1,[2,4,8],3]);
;hashTwo(['a','b','c'], [1,2]);
;hashTwo([], []);
/*
=!EXPECTSTART!=
hashTwo(['a','b','c'], [1,2,3]) ==> { a:1, b:2, c:3 }
hashTwo(['a','b'], [1,[2,4,8],3]) ==> { a:1, b:[ 2, 4, 8 ] }
hashTwo(['a','b','c'], [1,2]) ==> { a:1, b:2, c:undefined }
hashTwo([], []) ==> {}
=!EXPECTEND!=
*/
- Output:
prompt$ jsish -u hashTwo.jsi [PASS] hashTwo.jsi
Use jsish --U hashTwo.jsi to see echo mode test lines.
Julia
Using comprehension:
k = ["a", "b", "c"]
v = [1, 2, 3]
Dict(ki => vi for (ki, vi) in zip(k, v))
Using constructor:
Dict(zip(keys, values))
Specifying types:
Dict{String,Int32}(zip(keys, values))
K
The keys in a dictionary must be a symbol.
a: `zero `one `two / symbols
b: 0 1 2
d:. a,'b / create the dictionary
.((`zero;0;)
(`one;1;)
(`two;2;))
d[`one]
1
Here we use integers as keys (which must be converted to symbols) and strings as values (here also converted to symbols).
keys: !10 / 0..9
split:{1_'(&x=y)_ x:y,x}
vals:split["zero one two three four five six seven eight nine";" "]
s:{`$$x} / convert to symbol
d:. (s'keys),'s'vals
.((`"0";`zero;)
(`"1";`one;)
(`"2";`two;)
(`"3";`three;)
(`"4";`four;)
(`"5";`five;)
(`"6";`six;)
(`"7";`seven;)
(`"8";`eight;)
(`"9";`nine;))
$d[s 1] / leading "$" converts back to string
"one"
Kotlin
// version 1.1.0
fun main(args: Array<String>) {
val names = arrayOf("Jimmy", "Bill", "Barack", "Donald")
val ages = arrayOf(92, 70, 55, 70)
val hash = mapOf(*names.zip(ages).toTypedArray())
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}
- Output:
Jimmy aged 92 Bill aged 70 Barack aged 55 Donald aged 70
Lang5
: >table 2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table
langur
the easy way
writeln hash(fw/a b c d/, [1, 2, 3, 4])
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.
val new = foldfrom(
fn h, key, value:more(h, {key: value}),
{:}, fw/a b c d/, [1, 2, 3, 4],
)
writeln new
- Output:
{"d": 4, "a": 1, "b": 2, "c": 3}
Lasso
local(
array1 = array('a', 'b', 'c'),
array2 = array(1, 2, 3),
hash = map
)
loop(#array1 -> size) => {
#hash -> insert(#array1 -> get(loop_count) = #array2 -> get(loop_count))
}
#hash
-> map(a = 1, b = 2, c = 3)
LFE
(let* ((keys (list 'foo 'bar 'baz))
(vals (list '"foo data" '"bar data" '"baz data"))
(tuples (: lists zipwith
(lambda (a b) (tuple a b)) keys vals))
(my-dict (: dict from_list tuples)))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))
Lingo
keys = ["a","b","c"]
values = [1,2,3]
props = [:]
cnt = keys.count
repeat with i = 1 to cnt
props[keys[i]] = values[i]
end repeat
put props
-- ["a": 1, "b": 2, "c": 3]
LiveCode
put "a,b,c" into list1
put 10,20,30 into list2
split list1 using comma
split list2 using comma
repeat with i=1 to the number of elements of list1
put list2[i] into list3[list1[i]]
end repeat
combine list3 using comma and colon
put list3
-- ouput
-- a:10,b:20,c:30
Lua
function(keys,values)
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end
M2000 Interpreter
Module CheckAll {
Module CheckVectorType {
Dim Keys$(4), Values(4)
Keys$(0):= "one","two","three","four"
Values(0):=1,2,3,4
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values(i)
}
Print Dict("one")+Dict("four")=Dict("two")+Dict("three") ' true
}
Module CheckVectorType1 {
Dim Keys$(4), Values$(4)
Keys$(0):= "one","two","three","four"
Values$(0):="*","**","***","****"
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values$(i)
}
Print Dict$("one")+Dict$("four")=Dict$("two")+Dict$("three") ' true
}
CheckVectorType
CheckVectorType1
}
CheckAll
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
Module Checkit {
Function MakeHash(&a$(), &b$()) {
if dimension(a$())<>1 or dimension(b$())<>1 then Error "Only for one dimension arrays"
if len(a$())<>len(b$()) Then Error "Only for same size arrays"
start=dimension(a$(),1, 0)
end=dimension(a$(),1, 1)
start2=dimension(b$(),1, 0)
Inventory Hash
For i=start to end {
if Exist(hash, a$(i)) Then {
\\ s is a pointer to a stack object
s=hash(a$(i))
Stack s {Data i-start+start2}
} Else Append hash, a$(i):=Stack:=i-start+start2
}
=Hash
}
Module PrintKeyItems (hash, akey$, &b$()) {
\\ n=hash(akey$) ' use this if akey$ allways is a proper key
\\ and hide these two lines using \\
if not exist(hash, akey$) then Error "Key not exist"
n=Eval(hash)
For i=1 to Len(n) {
Print b$(stackitem(n,i)),
}
Print
}
Dim a$(2 to 5)
Dim b$(4 to 7)
a$(2)="A", "B","A","C"
b$(4)="A1","B1","A2", "C1"
MyHash=MakeHash(&a$(), &b$())
PrintkeyItems Myhash, "A", &b$() ' print A1 A2
PrintkeyItems Myhash, "B", &b$() ' print B1
PrintkeyItems Myhash, "C", &b$() ' print C1
}
Checkit
Maple
A := [1, 2, 3];
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );
Mathematica /Wolfram Language
Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
?? Hash
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three
MATLAB / Octave
See Associative arrays/Creation for clarification of limitations and differences between the two methods.
MATLAB/Octave: structs
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
% Assumes arrays are same size and valid types
s = struct;
if iscell(allVals)
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals{k};
end
else
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals(k);
end
end
end
- Output:
>> ages = StructFromArrays({'Joe' 'Bob' 'Sue'}, [21 35 27]) ages = Joe: 21 Bob: 35 Sue: 27
MATLAB only: containers.Map
containers.Map constructor provides this functionality already.
>> ages = containers.Map({'Joe' 'Bob' 'Sue'}, [21 35 27]); >> keys(ages) ans = 'Bob' 'Joe' 'Sue' >> values(ages) ans = [35] [21] [27]
MiniScript
keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]
d = {}
for i in range(keys.len-1)
d[keys[i]] = values[i]
end for
print d
- Output:
{"bar": "miss", "foo": "little", "val": "muffet"}
Neko
/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
var sprintf = $loader.loadprim("std@sprintf", 2)
var array_keys = $array("one",2,"three",4,"five")
var array_vals = $array("six",7,"eight",9,"zero")
var elements = $asize(array_keys)
var table = $hnew(elements)
var step = elements
while (step -= 1) >= 0 $hadd(table, $hkey(array_keys[step]), array_vals[step])
/*
$hiter accepts a hashtable and a function that accepts two args, key, val
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)
- Output:
prompt$ nekoc hash-two-arrays.neko prompt$ neko hash-two-arrays.n Hashed key: 13898426 Value: eight Hashed key: 38662 Value: six Hashed key: 2 Value: 7 Hashed key: 4 Value: 9 Hashed key: 737454 Value: zero
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);
}
}
NetRexx
REXX Style
/* NetRexx program ****************************************************
* 04.11.2012 Walter Pachl derived from REXX
**********************************************************************/
options replace format comments java crossref savelog symbols nobinary
values='triangle quadrilateral pentagon hexagon heptagon octagon' -
'nonagon decagon dodecagon'
keys ='three four five six seven eight nine ten twelve'
kcopy=keys
k='' /* initialize the arrays */
v=''
value='unknown'
Loop i=1 By 1 While kcopy>'' /* initialize the two arrays */
Parse kcopy ki kcopy; k[i]=ki
Parse values vi values; v[i]=vi
End
Loop j=1 To i-1
value[k[j]]=v[j]
End
Say 'Enter one of these words:'
Say ' 'keys
Parse Ask z
Say z '->' value[z]
Java Collections
NetRexx has access to Java's Collection objects too.
/* NetRexx */
options replace format comments java crossref symbols nobinary
vals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]
keys = [ 'k0', 'k1', 'k2', 'k3', 'k4', 'k5' ]
hash1 = Rexx
hash2 = Map
hash1 = HashMap()
hash2 = ''
makeHash(hash1, keys, vals) -- using a Map object (overloaded method)
makeHash(hash2, keys, vals) -- using a Rexx object (overloaded method)
return
-- Using a Java collection object
method makeHash(hash = Map, keys = Rexx[], vals = Rexx[]) static
loop k_ = 0 to keys.length - 1
hash.put(keys[k_], vals[k_])
end k_
key = Rexx
loop key over hash.keySet()
say key.right(8)':' hash.get(key)
end key
say
return
-- For good measure a version using the default Rexx object as a hash (associative array)
method makeHash(hash = Rexx, keys = Rexx[], vals = Rexx[]) static
loop k_ = 0 to keys.length - 1
hash[keys[k_]] = vals[k_]
end k_
loop key over hash
say key.right(8)':' hash[key]
end key
say
return
Nim
import tables, sequtils
let keys = @['a','b','c']
let values = @[1, 2, 3]
let table = toTable zip(keys, values)
Oberon-2
Works with oo2c version 2
MODULE HashFromArrays;
IMPORT
ADT:Dictionary,
Object:Boxed;
TYPE
Key= STRING;
Value= Boxed.LongInt;
PROCEDURE Do;
VAR
a: ARRAY 128 OF Key;
b: ARRAY 128 OF Value;
hash: Dictionary.Dictionary(Key,Value);
i: INTEGER;
BEGIN
hash := NEW(Dictionary.Dictionary(Key,Value));
a[0] := "uno";
a[1] := "dos";
a[2] := "tres";
a[3] := "cuatro";
b[0] := Boxed.ParseLongInt("1");
b[1] := Boxed.ParseLongInt("2");
b[2] := Boxed.ParseLongInt("3");
b[3] := Boxed.ParseLongInt("4");
i := 0;
WHILE (i < LEN(a)) & (a[i] # NIL) DO
hash.Set(a[i],b[i]);
INC(i)
END;
END Do;
BEGIN
Do;
END HashFromArrays.
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));
};
}
}
}
Objective-C
NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
OCaml
The idiomatic solution uses lists rather than arrays.
let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;
List.iter2 (Hashtbl.add hash) keys vals;;
The solution is similar with arrays.
let keys = [| "foo"; "bar"; "baz" |]
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.
If you want to use functional binary search trees instead of hash tables:
module StringMap = Map.Make (String);;
let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and map = StringMap.empty;;
let map = List.fold_right2 StringMap.add keys vals map;;
ooRexx
array1 = .array~of("Rick", "Mike", "David")
array2 = .array~of("555-9862", "555-5309", "555-6666")
-- if the index items are constrained to string objects, this can
-- be a directory too.
hash = .table~new
loop i = 1 to array1~size
hash[array1[i]] = array2[i]
end
Say 'Enter a name'
Parse Pull name
Say name '->' hash[name]
- Output:
Enter a name Rick Rick -> 555-9862
Oz
declare
fun {ZipRecord Keys Values}
{List.toRecord unit {List.zip Keys Values MakePair}}
end
fun {MakePair A B}
A#B
end
in
{Show {ZipRecord [a b c] [1 2 3]}}
PARI/GP
hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));
Pascal
program HashFromTwoArrays (Output);
uses
contnrs;
var
keys: array[1..3] of string = ('a', 'b', 'c');
values: array[1..3] of integer = ( 1, 2, 3 );
hash: TFPDataHashTable;
i: integer;
begin
hash := TFPDataHashTable.Create;
for i := low(keys) to high(keys) do
hash.add(keys[i], @values[i]);
writeln ('Length of hash table: ', hash.Count);
hash.Destroy;
end.
- Output:
% ./HashFromTwoArrays Length of hash table: 3
PascalABC.NET
begin
var Keys := Arr('aa','bb','cc');
var Values := Arr(1..3);
var dct := Dict(Keys.Zip(Values));
dct.Println;
end.
- Output:
(aa,1) (bb,2) (cc,3)
Perl
my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash;
@hash{@keys} = @vals;
Alternatively, using
:
use List::MoreUtils qw(zip);
my %hash = zip @keys, @vals;
Phix
You could of course make the values in the dictionary be indexes to valuearray instead, as shown commented out.
with javascript_semantics function make_hash(sequence keyarray, sequence valuearray) integer dict = new_dict() for i=1 to length(keyarray) do setd(keyarray[i],valuearray[i],dict) -- setd(keyarray[i],i,dict) end for return dict end function constant keyarray = {1,"two",PI} constant valuearray = {"one",2,PI} integer dict = make_hash(keyarray,valuearray) ?getd(1,dict) ?getd("two",dict) ?getd(PI,dict) --?valuearray[getd(1,dict)]
- Output:
"one" 2 3.141592654
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
- Output:
one 2 3.141592653589793 Unfound
PHP
$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);
$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
}
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).
- Output:
(map)[d = 4,c = 3,b = 2,a = 1,e = 5]
PicoLisp
(let (Keys '(one two three) Values (1 2 3))
(mapc println
(mapcar cons Keys Values) ) )
- Output:
(one . 1) (two . 2) (three . 3)
Pike
Any data type can be used as indices (keys) and values.
array indices = ({ "a", "b", 42 });
array values = ({ Image.Color(0,0,0), "hello", "world" });
mapping m = mkmapping( indices, values );
write("%O\n", m);
- Output:
([ /* 3 elements */ "a": Image.Color.black, "b": "hello" 42: "world", ])
Pop11
vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars i;
;;; Create hash table
vars ht = newmapping([], 500, 0, true);
;;; Loop over input arrays (vectors)
for i from 1 to length(keys) do
vals(i) -> ht(keys(i));
endfor;
PostScript
% push our arrays
[/a /b /c /d /e] [1 2 3 4 5]
% create a dict with it
{aload pop} dip let currentdict end
% show that we have created the hash
{= =} forall
PowerShell
function create_hash ([array] $keys, [array] $values) {
$h = @{}
if ($keys.Length -ne $values.Length) {
Write-Error -Message "Array lengths do not match" `
-Category InvalidData `
-TargetObject $values
} else {
for ($i = 0; $i -lt $keys.Length; $i++) {
$h[$keys[$i]] = $values[$i]
}
}
return $h
}
Prolog
% this one with side effect hash table creation
:-dynamic hash/2.
make_hash([],[]).
make_hash([H|Q],[H1|Q1]):-
assert(hash(H,H1)),
make_hash(Q,Q1).
:-make_hash([un,deux,trois],[[a,b,c],[d,e,f],[g,h,i]])
% this one without side effects
make_hash_pure([],[],[]).
make_hash_pure([H|Q],[H1|Q1],[hash(H,H1)|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).
PureBasic
Dim keys.s(3)
Dim vals.s(3)
NewMap Hash.s()
keys(0)="a" : keys(1)="b" : keys(2)="c" : keys(3)="d"
vals(0)="1" : vals(1)="2" : vals(2)="3" : vals(3)="4"
For n = 0 To 3
Hash(keys(n))= vals(n)
Next
ForEach Hash()
Debug Hash()
Next
Python
Shows off the dict comprehensions in Python 3 (that were back-ported to 2.7):
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = {key: value for key, value in zip(keys, values)}
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(zip(keys, values))
# Lazily, Python 2.3+, not 3.x:
from itertools import izip
hash = dict(izip(keys, values))
keys = ['a', 'b', 'c']
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):
>>> class Hashable(object):
def __hash__(self):
return id(self) ^ 0xBEEF
>>> my_inst = Hashable()
>>> my_int = 1
>>> my_complex = 0 + 1j
>>> my_float = 1.2
>>> my_string = "Spam"
>>> my_bool = True
>>> my_unicode = u'Ham'
>>> my_list = ['a', 7]
>>> my_tuple = ( 0.0, 1.4 )
>>> my_set = set(my_list)
>>> def my_func():
pass
>>> class my_class(object):
pass
>>> keys = [my_inst, my_tuple, my_int, my_complex, my_float, my_string,
my_bool, my_unicode, frozenset(my_set), tuple(my_list),
my_func, my_class]
>>> values = range(12)
>>> d = dict(zip(keys, values))
>>> for key, value in d.items(): print key, ":", value
1 : 6
1j : 3
Ham : 7
Spam : 5
(0.0, 1.3999999999999999) : 1
frozenset(['a', 7]) : 8
1.2 : 4
('a', 7) : 9
<function my_func at 0x0128E7B0> : 10
<class '__main__.my_class'> : 11
<__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
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 Wikipedia page on hash tables.
# Set up hash table
keys <- c("John Smith", "Lisa Smith", "Sam Doe", "Sandra Dee", "Ted Baker")
values <- c(152, 1, 254, 152, 153)
names(values) <- keys
# Get value corresponding to a key
values["Sam Doe"] # vals["Sam Doe"]
# Get all keys corresponding to a value
names(values)[values==152] # "John Smith" "Sandra Dee"
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))
Raku
(formerly Perl 6)
Using the "zipwith" meta-operator on the => pair composer:
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
Raven
[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals
$keys $vals combine as $hash
REXX
This REXX version allows multiple keys for a value, the keys are case sensitive.
/*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'
key.1='thuhree vour phive sicks zeaven ate nein den duzun'
key.2='three four five six seven eight nine ten twelve'
key.3='3 4 5 6 7 8 9 10 12'
key.4='III IV V VI VII VIII IX X XII'
key.5='iii iv v vi vii viii ix x xii'
hash.='───(not defined)───' /* [↑] blanks added to humorous keys */
/* just because it looks prettier.*/
do k=1 while key.k\==''
call hash vals,key.k /*hash the keys to the values. */
end /*k*/
parse arg query . /*obtain what was specified on the C.L.*/
if query\=='' then say 'key:' left(query,40) "value:" hash.query
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hash: parse arg @val,@key
do j=1 for words(@key); map= word(@key, j)
hash.map= word(@val, j)
end /*j*/
return
- output when using the input value of: phive
key: phive value: pentagon
- output when using the input value of: dingsta
key: dingsta value: ───(not defined)───
Ring
# Project : Hash from two arrays
list1="one two three"
list2="1 2 3"
a = str2list(substr(list1," ",nl))
b = str2list(substr(list2," ",nl))
c = list(len(a))
for i=1 to len(b)
temp = number(b[i])
c[temp] = a[i]
next
for i = 1 to len(c)
see c[i] + " " + i + nl
next
Output:
one 1 two 2 three 3
RPL
≪ 2 →LIST ≫ '→HASH' STO ≪ OVER 1 GET SWAP POS SWAP 2 GET SWAP GET ≫ 'HASH→' STO
{ "one" "two" "three" } { 1 2 3 } →HASH DUP 'MYHASH' STO MYHASH 2 HASH→
- Output:
2: { { 1 2 3 } { "one" "two" "three" } } 1: "two"
Ruby
keys = ['hal',666,[1,2,3]]
vals = ['ibm','devil',123]
hash = Hash[keys.zip(vals)]
p hash # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123}
#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ] # => 123
In Ruby 2.1 the method "to_h" was introduced:
keys = ['hal', 666, [1,2,3]]
vals = ['ibm', 'devil', 123]
keys.zip(vals).to_h
Rust
use std::collections::HashMap;
fn main() {
let keys = ["a", "b", "c"];
let values = [1, 2, 3];
let hash = keys.iter().zip(values.iter()).collect::<HashMap<_, _>>();
println!("{:?}", hash);
}
Sather
class ZIPPER{K,E} is
zip(k:ARRAY{K}, e:ARRAY{E}) :MAP{K, E}
pre k.size = e.size
is
m :MAP{K, E} := #;
loop m[k.elt!] := e.elt!; end;
return m;
end;
end;
class MAIN is
main is
keys:ARRAY{STR} := |"one", "three", "four"|;
values:ARRAY{INT} := |1, 3, 4|;
m ::= ZIPPER{STR,INT}::zip(keys, values);
loop
#OUT + m.pair! + " ";
end;
#OUT + "\n";
end;
end;
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.
// Testing
assert(map == Map(1 ->"A", 2 -> "B", 3 -> "C"))
println("Successfully completed without errors.")
Scheme
Using SRFI 69
(define (lists->hash-table keys values . rest)
(apply alist->hash-table (map cons keys values) rest))
Using association lists
;; 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)
;;
Using persistent associative arrays
You need to compile this code along with the persistent associative arrays code. And, yes, the hash function for that implementation can return floating point numbers, the way the one here does.
(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
;;
Side note: association lists can be used in either a persistent or non-persistent manner.
Seed7
$ include "seed7_05.s7i";
const type: numericHash is hash [string] integer;
var numericHash: myHash is numericHash.value;
const proc: main is func
local
var array string: keyList is [] ("one", "two", "three");
var array integer: valueList is [] (1, 2, 3);
var integer: number is 0;
begin
for number range 1 to length(keyList) do
myHash @:= [keyList[number]] valueList[number];
end for;
end func;
SenseTalk
set keyList to ["red", "green", "blue"]
set valueList to [150,0,128]
repeat with n=1 to the number of items in keyList
set map.(item n of keyList) to item n of valueList
end repeat
put map
--> (blue:"128", green:"0", red:"150")
Sidef
var keys = %w(a b c)
var vals = [1, 2, 3]
var hash = Hash()
hash{keys...} = vals...
say hash
Smalltalk
Array extend [
dictionaryWithValues: array [ |d|
d := Dictionary new.
1 to: ((self size) min: (array size)) do: [:i|
d at: (self at: i) put: (array at: i).
].
^ d
]
].
({ 'red' . 'one' . 'two' }
dictionaryWithValues: { '#ff0000'. 1. 2 }) displayNl.
Dictionary
withKeys:#('one' 'two' 'three')
andValues:#('eins' 'zwei' 'drei')
Dictionary withAssociations:{ 'one'->1 . 'two'->2 . 'three'->3 }
SNOBOL4
* # Fill arrays
keys = array(5); vals = array(5)
ks = 'ABCDE'; vs = '12345'
kloop i = i + 1; ks len(1) . keys<i> = :s(kloop)
vloop j = j + 1; vs len(1) . vals<j> = :s(vloop)
* # Create hash
hash = table(5)
hloop k = k + 1; hash<keys<k>> = vals<k> :s(hloop)
* # Test and display
ts = 'ABCDE'
tloop ts len(1) . ch = :f(out)
str = str ch ':' hash<ch> ' ' :(tloop)
out output = str
end
- Output:
A:1 B:2 C:3 D:4 E:5
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];
}
Standard ML
Using functional binary search trees instead of hash tables:
structure StringMap = BinaryMapFn (struct
type ord_key = string
val compare = String.compare
end);
val keys = [ "foo", "bar", "baz" ]
and vals = [ 16384, 32768, 65536 ]
and myMap = StringMap.empty;
val myMap = foldl StringMap.insert' myMap (ListPair.zipEq (keys, vals));
Using hash tables:
exception NotFound;
val keys = [ "foo", "bar", "baz" ]
and vals = [ 16384, 32768, 65536 ]
and hash = HashTable.mkTable (HashString.hashString, op=) (42, NotFound);
ListPair.appEq (HashTable.insert hash) (keys, vals);
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
}
Tcl
Arrays in Tcl are automatically associative,
i.e. there are no "not hashed arrays".
If we can take "arrays of equal length" to mean
"lists of equal length",
then the task might look like this:
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
- Output:
arr(bob) = plumber arr(fred) = barber arr(joe) = tailor
Alternatively, a dictionary could be used:
package require Tcl 8.5
set keys [list fred bob joe]
set values [list barber plumber tailor]
foreach a $keys b $values {
dict set jobs $a $b
}
puts "jobs: [dict get $jobs]"
- Output:
jobs: fred barber bob plumber joe tailor
TXR
One-liner, using quasiquoted hash syntax
$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))
One-liner, using hash-construct
function
$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))'
#H(() (c 3) (b 2) (a 1))
Explicit construction and stuffing
(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)))
$ ./txr hash-from-two.tl #H(() (c 3) (b 2) (a 1))
UNIX Shell
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
- Output:
bar => 456 baz => 789 foo => 123
UnixPipes
Using a sorted file as an associative array (see Creating an associative array for usage.)
cat <<VAL >p.values
apple
boy
cow
dog
elephant
VAL
cat <<KEYS >p.keys
a
b
c
d
e
KEYS
paste -d\ <(cat p.values | sort) <(cat p.keys | sort)
Ursala
There is a built-in operator for this.
keys = <'foo','bar','baz'>
values = <12354,145430,76748>
hash_function = keys-$values
test program:
#cast %nL
test = hash_function* <'bar','baz','foo','bar'>
- Output:
<145430,76748,12354,145430>
Vala
using Gee;
void main(){
// mostly copied from C# example
var hashmap = new HashMap<string, string>();
string[] arg_keys = {"foo", "bar", "val"};
string[] arg_values = {"little", "miss", "muffet"};
if (arg_keys.length == arg_values.length ){
for (int i = 0; i < arg_keys.length; i++){
hashmap[arg_keys[i]] = arg_values[i];
}
}
}
VBScript
VBScript (and Visual Basic in general) calls hashes "dictionary objects".
Set dict = CreateObject("Scripting.Dictionary")
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add os(n), owner(n)
Next
MsgBox dict.Item("Linux")
MsgBox dict.Item("MacOS")
MsgBox dict.Item("Windows")
- Output:
(in message boxes)
Linus Torvalds Apple Microsoft
Visual Basic
The VBScript version can be used in Visual Basic unchanged, although it requires a reference to the Microsoft Scripting Runtime (scrrun.dll).
Alternately, instead of a Dictionary
object,
you can also use a Collection
object,
which serves a similar purpose, without the inclusion
of an additional runtime library.
In fact, the only immediately-obvious difference between this
and the VBScript example is dict
's data type,
and the order that the arguments are passed to the Add
method.
Dim dict As New Collection
os = Array("Windows", "Linux", "MacOS")
owner = Array("Microsoft", "Linus Torvalds", "Apple")
For n = 0 To 2
dict.Add owner(n), os(n)
Next
Debug.Print dict.Item("Linux")
Debug.Print dict.Item("MacOS")
Debug.Print dict.Item("Windows")
WDTE
let a => import 'arrays';
let s => import 'stream';
let toScope keys vals =>
s.zip (a.stream keys) (a.stream vals)
->
s.reduce (collect (true)) (@ r scope kv =>
let [k v] => kv;
set scope k v;
)
;
Example:
toScope
['a'; 'b'; 'c']
[1; 2; 3]
: scope
-> known
-> a.stream
-> s.map (@ m k => [k; at scope k])
-> s.collect
-- io.writeln io.stdout
;
- Output:
[[a; 1]; [b; 2]; [c; 3]]
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)
}
- Output:
{'a': 1, 'b': 2, 'c': 3}
Wortel
Wortel has an inbuilt operator to do this: @hash
.
@hash ["a" "b" "c"] [1 2 3] ; returns {a 1 b 2 c 3}
This function can also be defined as:
^(@obj @zip)
Example:
@let {
hash ^(@obj @zip)
!!hash ["a" "b" "c"] [1 2 3]
}
- Returns:
{a 1 b 2 c 3}
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.
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)
- Output:
{2: second, 1: first, 3: third, 5: fifth, 4: fourth}
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);
]
- Output:
2 6
Yabasic
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
- Output:
Same as FreeBASIC entry.
zkl
keys:=T("a","b","c","d"); vals:=T(1,2,3,4);
d:=keys.zip(vals).toDictionary();
d.println();
d["b"].println();
- Output:
D(a:1,b:2,c:3,d:4) 2
- Programming Tasks
- Basic language learning
- Data Structures
- BASIC/Omit
- PowerBASIC/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- 11l
- ActionScript
- Ada
- Amazing Hopper
- Argile
- Arturo
- AutoHotkey
- AWK
- BASIC256
- BBC BASIC
- Bracmat
- Brat
- C
- C sharp
- C++
- Range-v3
- Ceylon
- Clojure
- Coco
- CoffeeScript
- ColdFusion
- Common Lisp
- Crystal
- D
- Déjà Vu
- Delphi
- System.SysUtils
- System.Generics.Collections
- Diego
- E
- EchoLisp
- Elixir
- Emacs Lisp
- EMal
- Erlang
- F Sharp
- Factor
- Falcon
- Fantom
- FreeBASIC
- Frink
- FutureBasic
- Gambas
- Go
- Groovy
- Harbour
- Haskell
- Huginn
- Icon
- Unicon
- Ioke
- J
- Java
- JavaScript
- Jq
- Jsish
- Julia
- K
- Kotlin
- Lang5
- Langur
- Lasso
- LFE
- Lingo
- LiveCode
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- MiniScript
- Neko
- Nemerle
- NetRexx
- Nim
- Oberon-2
- Objeck
- Objective-C
- OCaml
- OoRexx
- Oz
- PARI/GP
- Pascal
- Contnrs
- PascalABC.NET
- Perl
- Phix
- Phixmonti
- PHP
- Picat
- PicoLisp
- Pike
- Pop11
- PostScript
- Initlib
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- Raku
- Raven
- REXX
- Ring
- RPL
- Ruby
- Rust
- Sather
- Scala
- Scheme
- Seed7
- SenseTalk
- Sidef
- Smalltalk
- SNOBOL4
- Sparkling
- Standard ML
- Swift
- Tcl
- TXR
- UNIX Shell
- UnixPipes
- Ursala
- Vala
- Gee
- VBScript
- Visual Basic
- WDTE
- V (Vlang)
- Wortel
- Wren
- XPL0
- Yabasic
- Zkl
- Pages with too many expensive parser function calls