Associative array/Merging: Difference between revisions

m
Moved Vlang entry into correct alphabetical order.
m (Moved Vlang entry into correct alphabetical order.)
 
(27 intermediate revisions by 22 users not shown)
Line 43:
|}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V base = [‘name’ = ‘Rocket Skates’, ‘price’ = ‘12.75’, ‘color’ = ‘yellow’]
V update = [‘price’ = ‘15.25’, ‘color’ = ‘red’, ‘year’ = ‘1974’]
 
V result = copy(base)
result.update(update)
 
print(result)</syntaxhighlight>
 
{{out}}
<pre>
[color = red, name = Rocket Skates, price = 15.25, year = 1974]
</pre>
 
=={{header|Ada}}==
<syntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Containers.Indefinite_Ordered_Maps;
 
procedure Merge_Maps is
use Ada.Text_Io;
 
type Key_Type is new String;
type Value_Type is new String;
 
package Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Key_Type,
Element_Type => Value_Type);
use Maps;
 
function Merge (Original : Map; Update : Map) return Map is
Result : Map := Original;
Cur : Cursor := Update.First;
begin
while Has_Element (Cur) loop
if Original.Contains (Key (Cur)) then
Result.Replace_Element (Result.Find (Key (Cur)),
Element (Cur));
else
Result.Insert (Key (Cur), Element (Cur));
end if;
Next (Cur);
end loop;
return Result;
end Merge;
 
procedure Put_Map (M : Map) is
Cur : Cursor := M.First;
begin
while Has_Element (Cur) loop
Put (String (Key (Cur)));
Set_Col (12);
Put (String (Element (Cur)));
New_Line;
Next (Cur);
end loop;
end Put_Map;
 
Original : Map;
Update : Map;
Result : Map;
begin
Original.Insert ("name", "Rocket Skates");
Original.Insert ("price", "12.75");
Original.Insert ("color", "yellow");
 
Update.Insert ("price", "15.25");
Update.Insert ("color", "red");
Update.Insert ("year", "1974");
 
Result := Merge (Original, Update);
 
Put_Line ("Original:");
Put_Map (Original);
New_Line;
 
Put_Line ("Update:");
Put_Map (Update);
New_Line;
 
Put_Line ("Result of merge:");
Put_Map (Result);
New_Line;
 
end Merge_Maps;</syntaxhighlight>
{{out}}
<pre>Original:
color yellow
name Rocket Skates
price 12.75
 
Update:
color red
price 15.25
year 1974
 
Result of merge:
color red
name Rocket Skates
price 15.25
year 1974</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the associative array implementations in [[ALGOL_68/prelude]].
<langsyntaxhighlight lang="algol68"># associative array merging #
# the modes allowed as associative array element values - change to suit #
Line 98 ⟶ 201:
);
e := NEXT c
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 111 ⟶ 214:
The method with AppleScript "records" is to concatenate them. The result is a third record containing the labels from both contributors, the values from the record to the left of the operator being kept where labels are shared. The bars with some of the labels below are to distinguish them as "user" labels from tokenised ones that are provided as standards for use by scriptable applications and scripting additions. However, merging records works with tokenised labels too.
 
<langsyntaxhighlight lang="applescript">set baseRecord to {|name|:"Rocket Skates", price:12.75, |color|:"yellow"}
set updateRecord to {price:15.25, |color|:"red", |year|:1974}
 
set mergedRecord to updateRecord & baseRecord
return mergedRecord</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">{price:15.25, |color|:"red", |year|:1974, |name|:"Rocket Skates"}</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">details: #[name: "Rocket Skates" price: 12.75 colour: 'yellow]
newDetails: extend details #[price: 15.25 colour: 'red year: 1974]
 
print newDetails</syntaxhighlight>
 
{{out}}
 
<pre>[name:Rocket Skates price:15.25 colour:red year:1974]</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">merge(base, update){
Merged := {}
for k, v in base
Line 128 ⟶ 242:
Merged[k] := v
return Merged
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">base := {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update := {"price":15.25, "color":"red", "year":1974}
Merged := merge(base, update)
for k, v in Merged
result .= k " : " v "`n"
MsgBox % result</langsyntaxhighlight>
Outputs:<pre>color : red
name : Rocket Skates
Line 141 ⟶ 255:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
Line 169 ⟶ 283:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 190 ⟶ 304:
 
=={{header|B4X}}==
<langsyntaxhighlight lang="b4x">Dim m1 As Map = CreateMap("name": "Rocket Skates", "price": 12.75, "color": "yellow")
Dim m2 As Map = CreateMap("price": 15.25, "color": "red", "year": 1974)
Dim merged As Map
Line 199 ⟶ 313:
Next
Next
Log(merged)</langsyntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<lang bacon>DECLARE base$, update$, merge$ ASSOC STRING
<syntaxhighlight lang="bacon">DECLARE base$, update$, merge$ ASSOC STRING
 
base$("name") = "Rocket Skates"
Line 228 ⟶ 343:
FOR x$ IN OBTAIN$(merge$)
PRINT x$, " : ", merge$(x$)
NEXT</langsyntaxhighlight>
{{out}}
<pre>Base array
Line 247 ⟶ 362:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <string>
#include <map>
Line 274 ⟶ 389:
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 284 ⟶ 399:
</pre>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 310 ⟶ 425:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 319 ⟶ 434:
 
=={{header|Clojure}}==
<syntaxhighlight lang="clojure">
<lang Clojure>
(defn update-map [base update]
(merge base update))
Line 329 ⟶ 444:
"color" "red"
"year" "1974"})
</syntaxhighlight>
</lang>
 
{{out}}
Line 337 ⟶ 452:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = { "price" => 15.25, "color" => "red", "year" => 1974 }
 
puts base.merge(update)</langsyntaxhighlight>
 
{{out}}
<pre>{"name" => "Rocket Skates", "price" => 15.25, "color" => "red", "year" => 1974}
</pre>
 
=={{header|Common Lisp}}==
In Common Lisp, the value of a key in an alist or a plist is defined as the first value in the list with a matching key or indicator. Thus, all that is necessary to implement this algorithm for either is the following:
<syntaxhighlight lang="lisp">
(append list2 list1)
</syntaxhighlight>
 
These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
<syntaxhighlight lang="lisp">
(defun merge-alists (alist1 alist2)
(nconc
(loop :for pair1 :in alist1
:for pair2 := (assoc (car pair1) alist2)
:do (setf alist2 (remove pair2 alist2))
:collect (or pair2 pair1))
alist2))
 
(defun merge-plists (plist1 plist2)
(let ((res '()))
(loop :for (key val) :on plist1 :by #'cddr
:do (setf (getf res key) val))
(loop :for (key val) :on plist2 :by #'cddr
:do (setf (getf res key) val))
res))
</syntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="javascript">
main() {
var base = {
Line 369 ⟶ 509:
 
}
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Associative_arrayMerging;
 
Line 416 ⟶ 556:
end.
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 426 ⟶ 566:
=={{header|Elixir}}==
Elixir has a built-in hashmap type, called [https://hexdocs.pm/elixir/Map.html Map].
<langsyntaxhighlight Elixirlang="elixir">base = %{name: "Rocket Skates", price: 12.75, color: "yellow"}
update = %{price: 15.25, color: "red", year: 1974}
result = Map.merge(base, update)
IO.inspect(result)</langsyntaxhighlight>
{{out}}
<pre>%{color: "red", name: "Rocket Skates", price: 15.25, year: 1974}</pre>
The above sample uses [https://hexdocs.pm/elixir/Atom.html atoms] as the key type. If strings are needed, the <code>base</code> map would look like this:
<langsyntaxhighlight Elixirlang="elixir">base = %{"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
type N = |Price of float|Name of string|Year of int|Colour of string
let n=Map<string,N>[("name",Name("Rocket Skates"));("price",Price(12.75));("colour",Colour("yellow"))]
Line 442 ⟶ 582:
let ng=(Map.toList n)@(Map.toList g)|>Map.ofList
printfn "%A" ng
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 454 ⟶ 594:
The <code>assoc-union</code> word does this. <code>assoc-union!</code> is a variant that mutates the first associative array.
{{works with|Factor|0.99 2019-10-06}}
<langsyntaxhighlight lang="factor">USING: assocs prettyprint ;
 
{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
{ { "price" 15.25 } { "color" "red" } { "year" 1974 } }
assoc-union .</langsyntaxhighlight>
{{out}}
<pre>
Line 468 ⟶ 608:
}
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef base = @{@"name" :@"Rocket Skates", @"price":@12.75, @"color":@"yellow"}
CFDictionaryRef update = @{@"price":@15.25, @"color":@"red", @"year":@1974}
CFMutableDictionaryRef merged = fn MutableDictionaryWithDictionary( base )
MutableDictionaryAddEntriesFromDictionary( merged, update )
print merged
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 492 ⟶ 650:
result := merge(base, update)
fmt.Println(result)
}</langsyntaxhighlight>
 
{{out}}
Line 502 ⟶ 660:
There are various approaches, all of which would be strictly typed.<br>
For example, if we want to treat the input and output records as all sharing the same type:
<langsyntaxhighlight lang="haskell">data Item = Item
{ name :: Maybe String
, price :: Maybe Float
Line 518 ⟶ 676:
itemFromMerge
(Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing)
(Item Nothing (Just 15.25) (Just "red") (Just 1974))</langsyntaxhighlight>
{{Out}}
<pre>Item {name = Just "Rocket Skates", price = Just 15.25, color = Just "red", year = Just 1974}</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="unicon">procedure main()
local base, update, master, f, k
 
Line 544 ⟶ 702:
write(k, " = ", master[k])
}
end</langsyntaxhighlight>
 
{{out}}
Line 554 ⟶ 712:
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
Line 561 ⟶ 719:
get=: [: > ((i.~ keys)~ <)~ { values@:] NB. key get (associative array)
pair=: [: |: <;._2;._2
</syntaxhighlight>
</lang>
Exercise the definitions. Interactive J prompts with 3 space indentation.
<pre>
Line 613 ⟶ 771:
 
=={{header|Java}}==
<p>
<lang java>import java.util.*;
See also, [https://rosettacode.org/wiki/Associative_array/Creation#Java Java - Associative array/Creation].
</p>
<p>
This task illustrates the difference between statically typed languages, and dynamically typed.<br />
With exception to the <code>var</code> keyword, Java is statically typed.
So, using an undefined, non-static, <kbd>value</kbd>, creates a trivial situation.
</p>
<p>
A good way to understand this task is that it's not possible in a static-typed language.<br />
It defeats the purpose of defining the data-type.<br />
For Java, if you're going to use <code>Object</code> as your data-type, you need to re-evaluate the method of abstraction.
</p>
<p>
Java offers <kbd>generics</kbd>, <kbd>interfaces</kbd>, and <kbd>abstract classes</kbd> for this task.
</p>
<p>
Considering this, to complete this specific task, I would just store the values as <kbd>strings</kbd>.
</p>
<syntaxhighlight lang="java">
import java.util.LinkedHashMap;
import java.util.Map;
</syntaxhighlight>
<syntaxhighlight lang="java">
Map<String, String> mapA = new LinkedHashMap<>();
mapA.put("name", "Rocket Skates");
mapA.put("price", "12.75");
mapA.put("color", "yellow");
 
Map<String, String> mapB = new LinkedHashMap<>();
class MergeMaps {
mapB.put("price", "15.25");
public static void main(String[] args) {
mapB.put("color", "red");
Map<String, Object> base = new HashMap<>();
basemapB.put("nameyear", "Rocket Skates1974");
base.put("price", 12.75);
base.put("color", "yellow");
Map<String, Object> update = new HashMap<>();
update.put("price", 15.25);
update.put("color", "red");
update.put("year", 1974);
 
Map<String, ObjectString> resultmapC = new HashMapLinkedHashMap<>(base);
resultmapC.putAll(updatemapA);
mapC.putAll(mapB);
</syntaxhighlight>
To show that the original <kbd>map</kbd>s are not affected.
<syntaxhighlight lang="java">
for(Map.Entry<String, String> entry : mapA.entrySet())
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
 
for(Map.Entry<String, String> entry : mapB.entrySet())
System.out.println(result);
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
}
 
}</lang>
for(Map.Entry<String, String> entry : mapC.entrySet())
{{output}}
System.out.printf("%-20s%s%n", entry.getKey(), entry.getValue());
<pre>{name=Rocket Skates, color=red, year=1974, price=15.25}</pre>
</syntaxhighlight>
<pre>
name Rocket Skates
price 12.75
color yellow
</pre>
<pre>
price 15.25
color red
year 1974
</pre>
<pre>
name Rocket Skates
price 15.25
color red
year 1974
</pre>
<p>
While not recommended, due to scalability, if you did want to use an <code>Object</code> as the value, you could use the following implementation.<br />
This will produce the same output as above.
</p>
<syntaxhighlight lang="java">
Map<String, Object> mapA = new LinkedHashMap<>();
mapA.put("name", "Rocket Skates");
mapA.put("price", 12.75);
mapA.put("color", "yellow");
 
Map<String, Object> mapB = new LinkedHashMap<>();
mapB.put("price", 15.25);
mapB.put("color", "red");
mapB.put("year", 1974);
 
Map<String, Object> mapC = new LinkedHashMap<>();
mapC.putAll(mapA);
mapC.putAll(mapB);
</syntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 653 ⟶ 874:
null, 2
))
})();</langsyntaxhighlight>
{{Out}}
<pre>{
Line 661 ⟶ 882:
"year": 1974
}</pre>
 
=={{header|jq}}==
 
Mapping “associative array” to “JSON object” in the natural way, the specified operation corresponds exactly to addition in jq, so that if A and B are the first and second objects respectively, then the jq expression `A + B` will yield the required result (as a JSON object).
 
=={{header|Julia}}==
Line 702 ⟶ 927:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">
fun main() {
val base = HashMap<String,String>()
Line 722 ⟶ 947:
println("merged: $merged")
}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 731 ⟶ 956:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}
 
Line 748 ⟶ 973:
for key,val in pairs(result) do
print(string.format("%s: %s", key, val))
end</langsyntaxhighlight>
 
{{output}}
Line 755 ⟶ 980:
year: 1974
name: Rocket Skates</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">a1 = <|"name" -> "Rocket Skates", "price" -> 12.75, "color" -> "yellow"|>;
a2 = <|"price" -> 15.25, "color" -> "red", "year" -> 1974|>;
Merge[{a1, a2}, Last]</syntaxhighlight>
{{out}}
<pre><|"name" -> "Rocket Skates", "price" -> 15.25, "color" -> "red", "year" -> 1974|></pre>
 
=={{header|MiniScript}}==
MiniScript supports merging maps with the + operator.
<langsyntaxhighlight MiniScriptlang="miniscript">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
result = base + update
 
print result</langsyntaxhighlight>
 
{{output}}
Line 769 ⟶ 1,001:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import tables
 
let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
Line 778 ⟶ 1,010:
t3[key] = value
 
echo t3</langsyntaxhighlight>
 
{{out}}
Line 785 ⟶ 1,017:
=={{header|Objective-C}}==
{{works with|Cocoa}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main(void) {
Line 798 ⟶ 1,030:
}
return 0;
}</langsyntaxhighlight>
{{output}}
<pre>{
Line 806 ⟶ 1,038:
year = 1974;
}</pre>
 
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
 
Note that, given OCaml's strong typing, we must declare a type here for the 3-type data.
In general, would need the specific data type for the task, or use a PPX rewriter (effectively a compiler middleware) that can rewrite code based on dynamic type extensions.
 
Helper code for all 3 versions:
<syntaxhighlight lang="ocaml">
type ty =
| TFloat of float
| TInt of int
| TString of string
 
type key = string
type assoc = string * ty
 
let string_of_ty : ty -> string = function
| TFloat x -> string_of_float x
| TInt i -> string_of_int i
| TString s -> s
 
let print_pair key el =
Printf.printf "%s: %s\n" key (string_of_ty el)
;;
</syntaxhighlight>
 
Association list : naive and functional approach.
<syntaxhighlight lang="ocaml">
let l1 : assoc list = [
("name", TString "Rocket Skates");
("price", TFloat 12.75);
("color", TString "yellow")
] ;;
 
let l2 : assoc list = [
("price", TFloat 15.25);
("color", TString "red");
("year", TInt 1974)
] ;;
 
let rec merge_assoc_list (base_list : assoc list) (add_list : assoc list) : assoc list =
List.fold_left
(fun l (key, val_) ->
(key, val_) :: (List.remove_assoc key l)
)
base_list
add_list
;;
 
let l' = merge_assoc_list l1 l2 ;;
</syntaxhighlight>
 
Binary tree/Map functor : proper functional approach.
{{works with|OCaml|above 4.03 for union function}}
<syntaxhighlight lang="ocaml">
module StringMap = Map.Make(String) ;;
 
let print_map = StringMap.iter print_pair ;;
 
let map_merge (base : ty StringMap.t) (add : ty StringMap.t) : ty StringMap.t =
StringMap.union (fun key v1 v2 -> Some v2) base add
;;
 
let m1 = StringMap.(
empty
|> add "name" (TString "Rocket Skates")
|> add "price" (TFloat 12.75)
|> add "color" (TString "yellow")
) ;;
 
let m2 = StringMap.(
empty
|> add "price" (TFloat 15.25)
|> add "color" (TString "red")
|> add "year" (TInt 1974)
) ;;
 
let m' = map_merge m1 m2 ;;
 
print_map m' ;;
</syntaxhighlight>
 
Hash table : imperative/mutable approach.
<syntaxhighlight lang="ocaml">
(* Updates the base table with the bindings from add *)
let hash_merge (base : (string, ty) Hashtbl.t) (add : (string, ty) Hashtbl.t) : unit =
Hashtbl.iter (Hashtbl.replace base) add
 
let print_hashtbl t =
Hashtbl.iter print_pair t
 
let h1 : (string, ty) Hashtbl.t = Hashtbl.create 10 ;;
Hashtbl.add h1 "name" (TString "Rocket Skates") ;;
Hashtbl.add h1 "price" (TFloat 12.75) ;;
Hashtbl.add h1 "color" (TString "yellow") ;;
 
let h2 : (string, ty) Hashtbl.t = Hashtbl.create 10 ;;
Hashtbl.add h2 "price" (TFloat 15.25) ;;
Hashtbl.add h2 "color" (TString "red") ;;
Hashtbl.add h2 "year" (TInt 1974) ;;
 
hash_merge h1 h2 ;;
 
print_hashtbl h1 ;;
</syntaxhighlight>
 
=={{header|Ol}}==
Since version 3.1.1 function `ff-union` changed from `(ff-union a1 a2 collide)` to `(ff-union collide a1 a2 ...)`!
<lang scheme>
 
<syntaxhighlight lang="scheme">
(define a1 {
'name "Rocket Skates"
Line 825 ⟶ 1,165:
 
(define (collide a b) b) ; will use new key value
(print "merged a1 a2: " (ff-union collide a1 a2 collide))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 835 ⟶ 1,175:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 849 ⟶ 1,189:
$merge{$_} = [$base{$_}] for keys %base;
push @{$merge{$_}}, $more{$_} for keys %more;
printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;</langsyntaxhighlight>
{{output}}
<pre>Update
Line 864 ⟶ 1,204:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>integer d1 = new_dict({{"name","Rocket Skates"},{"price",12.75},{"color","yellow"}}),
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
d2 = new_dict({{"price",15.25},{"color","red"},{"year",1974}}),
<span style="color: #004080;">integer</span> <span style="color: #000000;">d1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"name"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Rocket Skates"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"price"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">12.75</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"color"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"yellow"</span><span style="color: #0000FF;">}}),</span>
d3 = new_dict(d1)
<span style="color: #000000;">d2</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">({{</span><span style="color: #008000;">"price"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15.25</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"color"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"red"</span><span style="color: #0000FF;">},{</span><span style="color: #008000;">"year"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1974</span><span style="color: #0000FF;">}}),</span>
function merger(object key, data, /*user_data*/) setd(key,data,d3) return 1 end function
<span style="color: #000000;">d3</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d1</span><span style="color: #0000FF;">)</span>
traverse_dict(merger,NULL,d2)
<span style="color: #008080;">function</span> <span style="color: #000000;">merger</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*user_data*/</span><span style="color: #0000FF;">)</span> <span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #000000;">data</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d3</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">return</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
include builtins/map.e
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">merger</span><span style="color: #0000FF;">,</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d2</span><span style="color: #0000FF;">)</span>
?pairs(d3)</lang>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #000000;">map</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">pairs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d3</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 877 ⟶ 1,220:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
def scand /# dict key -- dict n #/
Line 923 ⟶ 1,266:
 
pstack
</syntaxhighlight>
</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 932 ⟶ 1,275:
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?></langsyntaxhighlight>
{{output}}
<pre>Array
Line 943 ⟶ 1,286:
 
Alternative:
<langsyntaxhighlight lang="php"><?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
Line 949 ⟶ 1,292:
$result = array_merge($base, $update);
print_r($result);
?></langsyntaxhighlight>
{{output}}
<pre>Array
Line 958 ⟶ 1,301:
[year] => 1974
)</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">NewMap m1.s()
NewMap m2.s()
NewMap m3.s()
 
m1("name")="Rocket Skates"
m1("price")="12.75"
m1("color")="yellow"
 
m2("price")="15.25"
m2("color")="red"
m2("year")="1974"
 
CopyMap(m1(),m3())
ForEach m2()
m3(MapKey(m2()))=m2()
Next
 
ForEach m3()
Debug MapKey(m3())+" : "+m3()
Next</syntaxhighlight>
{{out}}
<pre>price : 15.25
color : red
year : 1974
name : Rocket Skates</pre>
 
=={{header|Python}}==
As of Python 3.5, this can be solved with the dictionary unpacking operator.
{{works with|Python|3.5+}}
<langsyntaxhighlight Pythonlang="python">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
result = {**base, **update}
 
print(result)</langsyntaxhighlight>
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
 
;Alternative:
<langsyntaxhighlight Pythonlang="python">base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
Line 978 ⟶ 1,349:
result.update(update)
 
print(result)</langsyntaxhighlight>
{{output}}
<pre>{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}</pre>
 
;New alternative using '|'
 
<syntaxhighlight lang="python">Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
>>> update = {"price":15.25, "color":"red", "year":1974}
>>> result = base | update
>>> result
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}
>>> </syntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket/base
 
(require racket/hash)
Line 1,000 ⟶ 1,382:
 
(hash-union base-data update-data #:combine (λ (a b) b)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,010 ⟶ 1,392:
I must say I somewhat disagree with the terminology. The requested operation is an update not a merge. Demonstrate both an update and a merge. Associative arrays are commonly called hashes in Raku.
 
<syntaxhighlight lang="raku" perl6line># Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
Line 1,025 ⟶ 1,407:
 
# Demonstrate unmutated hashes
say "\n", %base, "\n", %update;</langsyntaxhighlight>
{{out}}
<pre>{color => yellow, name => Rocket Skates, price => 12.75}
Line 1,065 ⟶ 1,447:
The double quotes that surround the string (character) items (as shown in the task's preamble) weren't included for this presentation,
<br>although they could easily be added.
<langsyntaxhighlight lang="rexx">/*REXX program merges two associative arrays (requiring an external list of indices). */
$.= /*define default value(s) for arrays. */
@.wAAn= 21; @.wKey= 7; @.wVal= 7 /*max widths of: AAname, keys, values.*/
Line 1,097 ⟶ 1,479:
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
end /*j*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
<pre>
Line 1,118 ⟶ 1,500:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
 
Line 1,142 ⟶ 1,524:
see list1[n][1] + " = " + list1[n][2] + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,152 ⟶ 1,534:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
 
result = base.merge(update)
p result</langsyntaxhighlight>
{{output}}
<pre>{"name"=>"Rocket Skates", "price"=>15.25, "color"=>"red", "year"=>1974}</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::collections::HashMap;
 
fn main() {
Line 1,178 ⟶ 1,560:
println!("{:#?}", original);
}
</syntaxhighlight>
</lang>
{{output}}
<pre>{
Line 1,186 ⟶ 1,568:
"price": "15.25",
}</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
'''Quick and Dirty'''
<br />
The procedures which access association lists (alist) in Scheme prefer the first matched item
in an alist. Hence, a merge may be implemented by simply appending the update alist to the
front of the base alist. The downside is this leaves a bunch of useless junk in the alist.
<syntaxhighlight lang="scheme">; Merge alists by appending the update list onto the front of the base list.
; (The extra '() is so that append doesn't co-opt the second list.)
(define append-alists
(lambda (base update)
(append update base '())))
 
; Test...
(printf "~%Merge using append procedure...~%")
; The original base and update alists.
(let ((base '(("name" . "Rocket Skates") ("price" . 12.75) ("color" . "yellow" )))
(update '(("price" . 15.25) ("color" . "red") ("year" . 1974))))
; Merge by appending the update list onto the front of the base list.
(let ((merged (append-alists base update)))
; Show that everything worked.
(printf "Merged alist:~%~s~%" merged)
(printf "Values from merged alist:~%")
(let loop ((keys '("name" "price" "color" "year")))
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</syntaxhighlight>
{{out}}
<pre>
Merge using append procedure...
Merged alist:
(("price" . 15.25) ("color" . "red") ("year" . 1974) ("name" . "Rocket Skates") ("price" . 12.75) ("color" . "yellow"))
Values from merged alist:
"name" -> "Rocket Skates"
"price" -> 15.25
"color" -> "red"
"year" -> 1974
</pre>
'''More True to Intent'''
<br />
This is more true to the intent of the Task. It generates a new alist with only the key/value
pairs needed.
<syntaxhighlight lang="scheme">; Merge the given alists. Prefer the items from the "update" alist.
; Returns a new list; the argument lists are not modified.
(define merge-alists
(lambda (base update)
(let ((merged (list-copy update))
(remains (list-copy base)))
(let loop ((shadowing merged))
(if (null? shadowing)
(append merged remains)
(begin (set! remains (remp (lambda (pair) (equal? (car pair) (caar shadowing)))
remains))
(loop (cdr shadowing))))))))
 
; Test...
(printf "~%Merge using defined merge-alists procedure...~%")
; The original base and update alists.
(let ((base '(("name" . "Rocket Skates") ("price" . 12.75) ("color" . "yellow" )))
(update '(("price" . 15.25) ("color" . "red") ("year" . 1974))))
; Merge using the defined merge-alists procedure.
(let ((merged (merge-alists base update)))
; Show that everything worked.
(printf "Merged alist:~%~s~%" merged)
(printf "Values from merged alist:~%")
(let loop ((keys '("name" "price" "color" "year")))
(unless (null? keys)
(printf "~s -> ~s~%" (car keys) (cdr (assoc (car keys) merged)))
(loop (cdr keys))))))</syntaxhighlight>
{{out}}
<pre>
Merge using defined merge-alists procedure...
Merged alist:
(("price" . 15.25) ("color" . "red") ("year" . 1974) ("name" . "Rocket Skates"))
Values from merged alist:
"name" -> "Rocket Skates"
"price" -> 15.25
"color" -> "red"
"year" -> 1974
</pre>
 
=={{header|SenseTalk}}==
In addition to setting individual property values, SenseTalk includes 5 built-in operations for modifying property lists, to: add properties, replace properties, remove properties, retain properties, and rename properties. The operation to replace properties is needed for this task.
<syntaxhighlight lang="sensetalk">set base to {name:"Rocket Skates", price:12.75, color:"yellow"}
 
set update to {price:15.25, color:"red", year:1974}
 
put "Base data: " & base
put "Update data: " & update
 
// replacing as an operator, to generate merged data on the fly:
put "Merged data: " & base replacing properties in update
 
// replace as a command, to modify base data in place:
replace properties of update in base
put "Base after update: " & base
</syntaxhighlight>
{{out}}
<pre>
Base data: {color:"yellow", name:"Rocket Skates", price:12.75}
Update data: {color:"red", price:15.25, year:1974}
Merged data: {color:"red", name:"Rocket Skates", price:15.25, year:1974}
Base after update: {color:"red", name:"Rocket Skates", price:15.25, year:1974}
</pre>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">base := Dictionary withAssociations:{
'name'-> 'Rocket Skates' .
'price' -> 12.75 .
Line 1,202 ⟶ 1,688:
declareAllFrom:update.
 
Transcript showCR: result.</langsyntaxhighlight>
{{out}}
<pre>Dictionary(name->Rocket Skates price->15.25 year->1974 color->red)</pre>
Line 1,208 ⟶ 1,694:
=={{header|Swift}}==
{{works with|Swift|5+}}
<langsyntaxhighlight lang="swift">let base : [String: Any] = ["name": "Rocket Skates", "price": 12.75, "color": "yellow"]
let update : [String: Any] = ["price": 15.25, "color": "red", "year": 1974]
 
let result = base.merging(update) { (_, new) in new }
 
print(result)</langsyntaxhighlight>
{{output}}
<pre>["price": 15.25, "name": "Rocket Skates", "color": "red", "year": 1974]</pre>
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">set dict1 [dict create name "Rocket Skates" price 12.75 color yellow]
set dict2 [dict create price 15.25 color red year 1974]
dict for {key val} [dict merge $dict1 $dict2] {
puts "$key: $val"
}</syntaxhighlight>
{{output}}
<pre>name: Rocket Skates
price: 15.25
color: red
year: 1974</pre>
 
=={{header|VBA}}==
3 ways to do this tasks :
First : With Arrays + Type
<syntaxhighlight lang="vb">
<lang vb>
Private Type Associative
Key As String
Line 1,276 ⟶ 1,774:
Next i
Debug.Print "-----------------------------"
End Sub</langsyntaxhighlight>
 
Second way (simply) : with the Scripting Dictionary Object :
<langsyntaxhighlight lang="vb">Sub Main_With_Dictionary()
Dim Base As Object, Update As Object, Merged As Object, K As Variant
'INIT VARIABLE
Line 1,301 ⟶ 1,799:
Debug.Print K, Merged(K)
Next K
End Sub</langsyntaxhighlight>
 
And the Third : With a Class Module (named ClassArrayAssociative)
The Class Module code:
<langsyntaxhighlight lang="vb">Option Explicit
 
Private mKey As String
Line 1,326 ⟶ 1,824:
Value = V
Key = K
End Sub</langsyntaxhighlight>
The Module code :
<langsyntaxhighlight lang="vb">Sub Main_With_Class()
Dim Base(2) As New ClassArrayAssociative, Up(2) As New ClassArrayAssociative
ReDim Result(UBound(Base)) As New ClassArrayAssociative
Line 1,370 ⟶ 1,868:
Next i
Debug.Print "-----------------------------"
End Sub</langsyntaxhighlight>
{{out}}
<pre>
Line 1,380 ⟶ 1,878:
-----------------------------</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
set d1=createobject("Scripting.Dictionary")
d1.add "name", "Rocket Skates"
d1.add "price", 12.75
d1.add "color", "yellow"
 
set d2=createobject("Scripting.Dictionary")
d2.add "price", 15.25
d2.add "color", "red"
d2.add "year", 1974
 
set d3=createobject("Scripting.Dictionary")
for each k1 in d1.keys
if not d3.exists(k1) then
d3.add k1, d1(k1)
else
d3(k1)=d1(k1)
end if
next
for each k2 in d2.keys
if not d3.exists(k2) then
d3.add k2, d2(k2)
else
d3(k2)=d2(k2)
end if
next
 
for each k3 in d3.keys
wscript.echo k3 & vbtab & d3(k3)
next
</syntaxhighlight>
{{out}}
<pre>
name Rocket Skates
price 15.25
color red
year 1974
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">type Generic = int|string|f64
type Assoc = map[string]Generic
 
fn merge(base Assoc, update Assoc) Assoc {
mut result := Assoc(map[string]Generic{})
for k, v in base {
result[k] = v
}
for k, v in update {
result[k] = v
}
return result
}
fn main() {
base := Assoc({"name": Generic("Rocket Skates"), "price": 12.75, "color": "yellow"})
update := Assoc({"price": Generic(15.25), "color": "red", "year": 1974})
result := merge(base, update)
for k,v in result {
println('$k: $v')
}
}</syntaxhighlight>
{{out}}
<pre>
name: Generic('Rocket Skates')
price: Generic(15.25)
color: Generic('red')
year: Generic(1974)
</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
Line 1,393 ⟶ 1,960:
var update = { "price": 15.25, "color": "red", "year": 1974 }
var merged = mergeMaps.call(base, update)
System.print(merged)</langsyntaxhighlight>
 
{{out}}
Line 1,401 ⟶ 1,968:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">base:=Dictionary(
"name", "Rocket Skates",
"price", 12.75,
Line 1,412 ⟶ 1,979:
update.pump( new:=base.copy() );
 
new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits