I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

Associative array/Merging

From Rosetta Code
Task
Associative array/Merging
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Define two associative arrays, where one represents the following "base" data:

Key Value
"name" "Rocket Skates"
"price" 12.75
"color" "yellow"

And the other represents "update" data:

Key Value
"price" 15.25
"color" "red"
"year" 1974

Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

Key Value
"name" "Rocket Skates"
"price" 15.25
"color" "red"
"year" 1974



ALGOL 68[edit]

Works with: ALGOL 68G version Any - tested with release 2.8.3.win32

Uses the associative array implementations in ALGOL_68/prelude.

# associative array merging                                                  #
 
# the modes allowed as associative array element values - change to suit #
MODE AAVALUE = UNION( STRING, INT, REAL );
# the modes allowed as associative array element keys - change to suit #
MODE AAKEY = STRING;
# initial value for an array element #
AAVALUE init element value = "";
 
# include the associative array code #
PR read "aArrayBase.a68" PR
 
# adds or replaces all elements from b into a #
PRIO UPDATE = 9;
OP UPDATE = ( REF AARRAY a, REF AARRAY b )REF AARRAY:
BEGIN
REF AAELEMENT e := FIRST b;
WHILE e ISNT nil element DO
a // key OF e := value OF e;
e := NEXT b
OD;
a
END # UPDATE # ;
 
# construct the associative arrays for the task #
REF AARRAY a := INIT LOC AARRAY;
REF AARRAY b := INIT LOC AARRAY;
a // "name" := "Rocket Skates";
a // "price" := 12.75;
a // "color" := "yellow";
b // "price" := 15.25;
b // "color" := "red";
b // "year" := 1974;
# merge the arrays #
REF AARRAY c := INIT LOC AARRAY;
c UPDATE a UPDATE b;
# show the merged array #
REF AAELEMENT e := FIRST c;
WHILE e ISNT nil element DO
print( ( key OF e
, ": "
, CASE value OF e
IN (STRING s): s
, (INT i): whole( i, 0 )
, (REAL r): fixed( r, -12, 2 )
OUT "????"
ESAC
, newline
)
);
e := NEXT c
OD
Output:
name: Rocket Skates
year: 1974
price:        15.25
color: red

AutoHotkey[edit]

merge(base, update){
Merged := {}
for k, v in base
Merged[k] := v
for k, v in update
Merged[k] := v
return Merged
}
Examples:
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
Outputs:
color : red
name : Rocket Skates
price : 15.25
year : 1974

AWK[edit]

 
# syntax: GAWK -f ASSOCIATIVE_ARRAY_MERGING.AWK
#
# sorting:
# PROCINFO["sorted_in"] is used by GAWK
# SORTTYPE is used by Thompson Automation's TAWK
#
BEGIN {
PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1
arr1["name"] = "Rocket Skates"
arr1["price"] = "12.75"
arr1["color"] = "yellow"
show_array(arr1,"base")
arr2["price"] = "15.25"
arr2["color"] = "red"
arr2["year"] = "1974"
show_array(arr2,"update")
for (i in arr1) { arr3[i] = arr1[i] }
for (i in arr2) { arr3[i] = arr2[i] }
show_array(arr3,"merged")
exit(0)
}
function show_array(arr,desc, i) {
printf("\n%s array\n",desc)
for (i in arr) {
printf("%-5s : %s\n",i,arr[i])
}
}
 
Output:
base array
color : yellow
name  : Rocket Skates
price : 12.75

update array
color : red
price : 15.25
year  : 1974

merged array
color : red
name  : Rocket Skates
price : 15.25
year  : 1974

B4X[edit]

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
merged.Initialize
For Each m As Map In Array(m1, m2)
For Each key As Object In m.Keys
merged.Put(key, m.Get(key))
Next
Next
Log(merged)

BaCon[edit]

DECLARE base$, update$, merge$ ASSOC STRING
 
base$("name") = "Rocket Skates"
base$("price") = "12.75"
base$("color") = "yellow"
 
PRINT "Base array"
FOR x$ IN OBTAIN$(base$)
PRINT x$, " : ", base$(x$)
NEXT
 
update$("price") = "15.25"
update$("color") = "red"
update$("year") = "1974"
 
PRINT NL$, "Update array"
FOR x$ IN OBTAIN$(update$)
PRINT x$, " : ", update$(x$)
NEXT
 
merge$() = base$()
merge$() = update$()
 
PRINT NL$, "Merged array"
FOR x$ IN OBTAIN$(merge$)
PRINT x$, " : ", merge$(x$)
NEXT
Output:
Base array
name : Rocket Skates
color : yellow
price : 12.75

Update array
year : 1974
color : red
price : 15.25

Merged array
name : Rocket Skates
year : 1974
color : red
price : 15.25

C++[edit]

#include <iostream>
#include <string>
#include <map>
 
template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
map_type result(update);
result.insert(original.begin(), original.end());
return result;
}
 
int main() {
typedef std::map<std::string, std::string> map;
map original{
{"name", "Rocket Skates"},
{"price", "12.75"},
{"color", "yellow"}
};
map update{
{"price", "15.25"},
{"color", "red"},
{"year", "1974"}
};
map merged(merge(original, update));
for (auto&& i : merged)
std::cout << "key: " << i.first << ", value: " << i.second << '\n';
return 0;
}
Output:
key: color, value: red
key: name, value: Rocket Skates
key: price, value: 15.25
key: year, value: 1974

C#[edit]

using System;
using System.Collections.Generic;
using System.Linq;
 
public class Program
{
public static void Main() {
var baseData = new Dictionary<string, object> {
["name"] = "Rocket Skates",
["price"] = 12.75,
["color"] = "yellow"
};
var updateData = new Dictionary<string, object> {
["price"] = 15.25,
["color"] = "red",
["year"] = 1974
};
var mergedData = new Dictionary<string, object>();
foreach (var entry in baseData.Concat(updateData)) {
mergedData[entry.Key] = entry.Value;
}
foreach (var entry in mergedData) {
Console.WriteLine(entry);
}
}
}
Output:
[name, Rocket Skates]
[price, 15.25]
[color, red]
[year, 1974]

Clojure[edit]

 
(defn update-map [base update]
(merge base update))
 
(update-map {"name" "Rocket Skates"
"price" "12.75"
"color" "yellow"}
{"price" "15.25"
"color" "red"
"year" "1974"})
 
Output:
{"name" "Rocket Skates", "price" "15.25", "color" "red", "year" "1974"}

Dart[edit]

 
main() {
var base = {
'name': 'Rocket Skates',
'price': 12.75,
'color': 'yellow'
};
 
var newData = {
'price': 15.25,
'color': 'red',
'year': 1974
};
 
var updated = Map.from( base ) // create new Map from base
..addAll( newData ); // use cascade operator to add all new data
 
assert( base.toString() == '{name: Rocket Skates, price: 12.75, color: yellow}' );
assert( updated.toString() == '{name: Rocket Skates, price: 15.25, color: red, year: 1974}');
 
 
}
 

Delphi[edit]

Translation of: C#
 
program Associative_arrayMerging;
 
{$APPTYPE CONSOLE}
 
uses
System.Generics.Collections;
 
type
TData = TDictionary<string, Variant>;
 
var
baseData, updateData, mergedData: TData;
entry: string;
 
begin
baseData := TData.Create();
baseData.Add('name', 'Rocket Skates');
baseData.Add('price', 12.75);
baseData.Add('color', 'yellow');
 
updateData := TData.Create();
updateData.Add('price', 15.25);
updateData.Add('color', 'red');
updateData.Add('year', 1974);
 
mergedData := TData.Create();
for entry in baseData.Keys do
mergedData.AddOrSetValue(entry, baseData[entry]);
 
for entry in updateData.Keys do
mergedData.AddOrSetValue(entry, updateData[entry]);
 
for entry in mergedData.Keys do
Writeln(entry, ' ', mergedData[entry]);
 
mergedData.Free;
updateData.Free;
baseData.Free;
 
Readln;
end.
 
 
Output:
price 15,25
year 1974
color red
name Rocket Skates

F#[edit]

 
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"))]
let g=Map<string,N>[("price",Price(15.25));("colour",Colour("red"));("year",Year(1974))]
let ng=(Map.toList n)@(Map.toList g)|>Map.ofList
printfn "%A" ng
 
Output:
map
  [("colour", Colour "red"); ("name", Name "Rocket Skates");
   ("price", Price 15.25); ("year", Year 1974)]

// Minimum positive multiple in base 10 using only 0 and 1. Nigel Galloway: March 9th., 2020

Factor[edit]

The assoc-union word does this. assoc-union! is a variant that mutates the first associative array.

Works with: Factor version 0.99 2019-10-06
USING: assocs prettyprint ;
 
{ { "name" "Rocket Skates" } { "price" 12.75 } { "color" "yellow" } }
{ { "price" 15.25 } { "color" "red" } { "year" 1974 } }
assoc-union .
Output:
V{
    { "name" "Rocket Skates" }
    { "price" 15.25 }
    { "color" "red" }
    { "year" 1974 }
}

Go[edit]

package main
 
import "fmt"
 
type assoc map[string]interface{}
 
func merge(base, update assoc) assoc {
result := make(assoc)
for k, v := range base {
result[k] = v
}
for k, v := range update {
result[k] = v
}
return result
}
 
func main() {
base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"}
update := assoc{"price": 15.25, "color": "red", "year": 1974}
result := merge(base, update)
fmt.Println(result)
}
Output:
map[color:red name:Rocket Skates price:15.25 year:1974]

Haskell[edit]

There are various approaches, all of which would be strictly typed.
For example, if we want to treat the input and output records as all sharing the same type:

data Item = Item
{ name :: Maybe String
, price :: Maybe Float
, color :: Maybe String
, year :: Maybe Int
} deriving (Show)
 
itemFromMerge :: Item -> Item -> Item
itemFromMerge (Item n p c y) (Item n1 p1 c1 y1) =
Item (maybe n pure n1) (maybe p pure p1) (maybe c pure c1) (maybe y pure y1)
 
main :: IO ()
main =
print $
itemFromMerge
(Item (Just "Rocket Skates") (Just 12.75) (Just "yellow") Nothing)
(Item Nothing (Just 15.25) (Just "red") (Just 1974))
Output:
Item {name = Just "Rocket Skates", price = Just 15.25, color = Just "red", year = Just 1974}

Icon and Unicon[edit]

procedure main()
local base, update, master, f, k
 
base := table()
base["name"] := "Rocket Skates"
base["price"] := 12.75
base["color"] := "yellow"
 
update := table()
update["price"] := 15.25
update["color"] := "red"
update["year"] := 1974
 
master := table()
every k := key((f := base | update)) do {
master[k] := f[k]
}
 
every k := key(master) do {
write(k, " = ", master[k])
}
end
Output:
prompt$ unicon -s merge.icn -x
color = red
name = Rocket Skates
price = 15.25
year = 1974

J[edit]

 
merge=: ,. NB. use: update merge original
compress=: #"1~ ~:@:keys
keys=: {.
values=: {:
get=: [: > ((i.~ keys)~ <)~ { [email protected]:] NB. key get (associative array)
pair=: [: |: <;._2;._2
 

Exercise the definitions. Interactive J prompts with 3 space indentation.

   ] D=: pair 0 :0
name;Rocket Skates;
price;12.75;
color;yellow;
)
┌─────────────┬─────┬──────┐
│name         │price│color │
├─────────────┼─────┼──────┤
│Rocket Skates│12.75│yellow│
└─────────────┴─────┴──────┘

   E=: pair 0 :0
price;15.25;
color;red;
year;1974;
)

   'color'get D
yellow

   'color'get E
red

   ] F=: E merge D
┌─────┬─────┬────┬─────────────┬─────┬──────┐
│price│color│year│name         │price│color │
├─────┼─────┼────┼─────────────┼─────┼──────┤
│15.25│red  │1974│Rocket Skates│12.75│yellow│
└─────┴─────┴────┴─────────────┴─────┴──────┘

   'color' get F
red

   ]G=: compress F
┌─────┬─────┬────┬─────────────┐
│price│color│year│name         │
├─────┼─────┼────┼─────────────┤
│15.25│red  │1974│Rocket Skates│
└─────┴─────┴────┴─────────────┘

   'no such key'get F
|index error: get
|   'no such key'    get F

   'color'get F
red

Java[edit]

import java.util.*;
 
class MergeMaps {
public static void main(String[] args) {
Map<String, Object> base = new HashMap<>();
base.put("name", "Rocket Skates");
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, Object> result = new HashMap<>(base);
result.putAll(update);
 
System.out.println(result);
}
}
Output:
{name=Rocket Skates, color=red, year=1974, price=15.25}

JavaScript[edit]

(() => {
'use strict';
 
console.log(JSON.stringify(
Object.assign({}, // Fresh dictionary.
{ // Base.
"name": "Rocket Skates",
"price": 12.75,
"color": "yellow"
}, { // Update.
"price": 15.25,
"color": "red",
"year": 1974
}
),
null, 2
))
})();
Output:
{
  "name": "Rocket Skates",
  "price": 15.25,
  "color": "red",
  "year": 1974
}

Julia[edit]

julia> dict1 = Dict("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow")
Dict{String,Any} with 3 entries:
  "name"  => "Rocket Skates"
  "price" => 12.75
  "color" => "yellow"

julia> dict2 = Dict("price" => 15.25, "color" => "red", "year" => 1974)
Dict{String,Any} with 3 entries:
  "price" => 15.25
  "year"  => 1974
  "color" => "red"

julia> merge(dict1, dict2)
Dict{String,Any} with 4 entries:
  "name"  => "Rocket Skates"
  "price" => 15.25
  "year"  => 1974
  "color" => "red"

julia> merge(dict2, dict1)
Dict{String,Any} with 4 entries:
  "name"  => "Rocket Skates"
  "price" => 12.75
  "year"  => 1974
  "color" => "yellow"

julia> union(dict1, dict2)
6-element Array{Pair{String,Any},1}:
  "name" => "Rocket Skates"
 "price" => 12.75
 "color" => "yellow"
 "price" => 15.25
  "year" => 1974
 "color" => "red"

Kotlin[edit]

 
fun main() {
val base = HashMap<String,String>()
val update = HashMap<String,String>()
 
base["name"] = "Rocket Skates"
base["price"] = "12.75"
base["color"] = "yellow"
 
update["price"] = "15.25"
update["color"] = "red"
update["year"] = "1974"
 
val merged = HashMap(base)
merged.putAll(update)
 
println("base: $base")
println("update: $update")
println("merged: $merged")
}
 
Output:
base: {color=yellow, price=12.75, name=Rocket Skates}
update: {color=red, year=1974, price=15.25}
merged: {name=Rocket Skates, color=red, year=1974, price=15.25}

Lua[edit]

base = {name="Rocket Skates", price=12.75, color="yellow"}
update = {price=15.25, color="red", year=1974}
 
--[[ clone the base data ]]--
result = {}
for key,val in pairs(base) do
result[key] = val
end
 
--[[ copy in the update data ]]--
for key,val in pairs(update) do
result[key] = val
end
 
--[[ print the result ]]--
for key,val in pairs(result) do
print(string.format("%s: %s", key, val))
end
Output:
price: 15.25
color: red
year: 1974
name: Rocket Skates

MiniScript[edit]

MiniScript supports merging maps with the + operator.

base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
result = base + update
 
print result
Output:
{"color": "red", "name": "Rocket Skates", "price": 15.25, "year": 1974}

Nim[edit]

import tables
 
let t1 = {"name": "Rocket Skates", "price": "12.75", "color": "yellow"}.toTable
let t2 = {"price": "15.25", "color": "red", "year": "1974"}.toTable
 
var t3 = t1 # Makes a copy.
for key, value in t2.pairs:
t3[key] = value
 
echo t3
Output:
{"name": "Rocket Skates", "year": "1974", "color": "red", "price": "15.25"}

Objective-C[edit]

Works with: Cocoa
#import <Foundation/Foundation.h>
 
int main(void) {
@autoreleasepool {
NSDictionary *base = @{@"name": @"Rocket Skates", @"price": @12.75, @"color": @"yellow"};
NSDictionary *update = @{@"price": @15.25, @"color": @"red", @"year": @1974};
 
NSMutableDictionary *result = [[NSMutableDictionary alloc] initWithDictionary:base];
[result addEntriesFromDictionary:update];
 
NSLog(@"%@", result);
}
return 0;
}
Output:
{
    color = red;
    name = "Rocket Skates";
    price = "15.25";
    year = 1974;
}

Ol[edit]

 
(define a1 {
'name "Rocket Skates"
'price 12.75
'color "yellow"
})
 
(define a2 {
'price 15.25
'color "red"
'year 1974
})
 
(print "a1: " a1)
(print "a2: " a2)
 
(define (collide a b) b) ; will use new key value
(print "merged a1 a2: " (ff-union a1 a2 collide))
 
Output:
a1: #ff((name . Rocket Skates) (price . 51/4) (color . yellow))
a2: #ff((price . 61/4) (color . red) (year . 1974))
merged a1 a2: #ff((name . Rocket Skates) (price . 61/4) (color . red) (year . 1974))

Perl[edit]

use strict;
use warnings;
 
my %base = ("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
my %more = ("price" => 15.25, "color" => "red", "year" => 1974);
 
print "Update\n";
my %update = (%base, %more);
printf "%-7s %s\n", $_, $update{$_} for sort keys %update;
 
print "\nMerge\n";
my %merge;
$merge{$_} = [$base{$_}] for keys %base;
push @{$merge{$_}}, $more{$_} for keys %more;
printf "%-7s %s\n", $_, join ', ', @{$merge{$_}} for sort keys %merge;
Output:
Update
color   red
name    Rocket Skates
price   15.25
year    1974

Merge
color   yellow, red
name    Rocket Skates
price   12.75, 15.25
year    1974

Phix[edit]

integer d1 = new_dict({{"name","Rocket Skates"},{"price",12.75},{"color","yellow"}}),
d2 = new_dict({{"price",15.25},{"color","red"},{"year",1974}}),
d3 = new_dict(d1)
function merger(object key, data, /*user_data*/) setd(key,data,d3) return 1 end function
traverse_dict(merger,NULL,d2)
include builtins/map.e
?pairs(d3)
Output:
{{"color","red"},{"name","Rocket Skates"},{"price",15.25},{"year",1974}}

Phixmonti[edit]

include ..\Utilitys.pmt
 
def scand /# dict key -- dict n #/
0 var flag
var ikey
len for
var i
i 1 2 tolist sget
ikey == if i var flag exitfor endif
endfor
flag
enddef
 
 
def getd /# dict key -- dict data #/
scand
dup if get 2 get nip else drop "Unfound" endif
enddef
 
 
def setd /# dict ( key data ) -- dict #/
1 get rot swap
scand
rot swap
dup if set else put endif
enddef
 
/# ---------- MAIN ---------- #/
 
( ( "name" "Rocket Skates" )
( "price" 12.75 )
( "color" "yellow" ) )
 
dup
 
( ( "price" 15.25 )
( "color" "red" )
( "year" 1974 ) )
 
len for
get rot swap setd swap
endfor
 
swap
 
pstack
 

PHP[edit]

<?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
 
$result = $update + $base; // Notice that the order is reversed
print_r($result);
?>
Output:
Array
(
    [price] => 15.25
    [color] => red
    [year] => 1974
    [name] => Rocket Skates
)

Alternative:

<?
$base = array("name" => "Rocket Skates", "price" => 12.75, "color" => "yellow");
$update = array("price" => 15.25, "color" => "red", "year" => 1974);
 
$result = array_merge($base, $update);
print_r($result);
?>
Output:
Array
(
    [name] => Rocket Skates
    [price] => 15.25
    [color] => red
    [year] => 1974
)

Python[edit]

As of Python 3.5, this can be solved with the dictionary unpacking operator.

Works with: Python version 3.5+
base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
result = {**base, **update}
 
print(result)
Output:
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}

Alternative:

base = {"name":"Rocket Skates", "price":12.75, "color":"yellow"}
update = {"price":15.25, "color":"red", "year":1974}
 
result = base.copy()
result.update(update)
 
print(result)
Output:
{'name': 'Rocket Skates', 'price': 15.25, 'color': 'red', 'year': 1974}

Racket[edit]

#lang racket/base
 
(require racket/hash)
 
(module+ test
(require rackunit)
 
(define base-data (hash "name" "Rocket Skates"
"price" 12.75
"color" "yellow"))
 
(define update-data (hash "price" 15.25
"color" "red"
"year" 1974))
 
(hash-union base-data update-data #:combine (λ (a b) b)))
 
Output:
'#hash(("color" . "red") ("name" . "Rocket Skates") ("price" . 15.25) ("year" . 1974))

Raku[edit]

(formerly Perl 6)

Works with: Rakudo version 2019.11

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.

# Show original hashes
say my %base = :name('Rocket Skates'), :price<12.75>, :color<yellow>;
say my %update = :price<15.25>, :color<red>, :year<1974>;
 
# Need to assign to anonymous hash to get the desired results and avoid mutating
# TIMTOWTDI
say "\nUpdate:\n", join "\n", sort %=%base, %update;
# Same
say "\nUpdate:\n", {%base, %update}.sort.join: "\n";
 
say "\nMerge:\n", join "\n", sort ((%=%base).push: %update)».join: ', ';
# Same
say "\nMerge:\n", ({%base}.push: %update)».join(', ').sort.join: "\n";
 
# Demonstrate unmutated hashes
say "\n", %base, "\n", %update;
Output:
{color => yellow, name => Rocket Skates, price => 12.75}
{color => red, price => 15.25, year => 1974}

Update:
color	red
name	Rocket Skates
price	15.25
year	1974

Update:
color	red
name	Rocket Skates
price	15.25
year	1974

Merge:
color	yellow, red
name	Rocket Skates
price	12.75, 15.25
year	1974

Merge:
color	yellow, red
name	Rocket Skates
price	12.75, 15.25
year	1974

{color => yellow, name => Rocket Skates, price => 12.75}
{color => red, price => 15.25, year => 1974}

REXX[edit]

The REXX language has no native support to acquire the keys of an associate array after they have been defined,  
so it must be performed at definition time,   but there are function packages to perform this function.

Some extra coding was added to support adjustable (maximum) widths for the displaying of the associate array names, keys, and values.

The double quotes that surround the string (character) items (as shown in the task's preamble) weren't included for this presentation,
although they could easily be added.

/*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.*/
call defAA 'base', "name Rocket Skates", 'price 12.75', "color yellow"
call defAA 'update', "price 15.25", "color red", 'year 1974'
call show 'base'
call show 'update'
call show 'new'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
defAA: procedure expose $. @.; parse arg AAn; new= 'new' /*get AA name; set NEW.*/
do j=2 to arg(); parse value arg(j) with key val /*obtain key and value.*/
$.AAn.key= val /*assign a value to a key for AAn. */
if wordpos(key, $.AAN.?keys)==0 then $.AAn.?keys= $.AAn.?keys key
/* [↑] add to key list if not in list.*/
$.new.key= val /*assign a value to a key for "new".*/
if wordpos(key, $.new.?keys)==0 then $.new.?keys= $.new.?keys key
/* [↑] add to key list if not in list.*/
@.wKey= max(@.wKey, length(key) ) /*find max width of a name of a key. */
@.wVal= max(@.wVal, length(val) ) /* " " " " " " " " value.*/
@.wAA = max(@.wAAn, length(AAn) ) /* " " " " " " " array.*/
end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: procedure expose $. @.; parse arg AAn; say; _= '═' /*set title char.*/
do j=1 for words($.AAn.?keys) /*process keys. */
if j==1 then say center('associate array', @.wAAn, _) ,
center("key" , @.wKey, _) ,
center('value' , @.wVal + 2, _)
key= word($.AAn.?keys, j) /*get the name of a key.*/
say center(AAn, @.wAAn) right(key, @.wKey) $.AAn.key /*show some information.*/
end /*j*/
return
output   when using the internal default inputs:
═══associate array═══ ══key══ ═════value═════
        base             name Rocket Skates
        base            price 12.75
        base            color yellow

═══associate array═══ ══key══ ═════value═════
       update           price 15.25
       update           color red
       update            year 1974

═══associate array═══ ══key══ ═════value═════
         new             name Rocket Skates
         new            price 15.25
         new            color red
         new             year 1974

Ruby[edit]

base = {"name" => "Rocket Skates", "price" => 12.75, "color" => "yellow"}
update = {"price" => 15.25, "color" => "red", "year" => 1974}
 
result = base.merge(update)
p result
Output:
{"name"=>"Rocket Skates", "price"=>15.25, "color"=>"red", "year"=>1974}

Rust[edit]

use std::collections::HashMap;
 
fn main() {
let mut original = HashMap::new();
original.insert("name", "Rocket Skates");
original.insert("price", "12.75");
original.insert("color", "yellow");
 
let mut update = HashMap::new();
update.insert("price", "15.25");
update.insert("color", "red");
update.insert("year", "1974");
 
original.extend(&update);
 
println!("{:#?}", original);
}
 
Output:
{
    "name": "Rocket Skates",
    "color": "red",
    "year": "1974",
    "price": "15.25",
}

Swift[edit]

Works with: Swift version 5+
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)
Output:
["price": 15.25, "name": "Rocket Skates", "color": "red", "year": 1974]

Wren[edit]

var mergeMaps = Fn.new { |m1, m2|
var m3 = {}
for (key in m1.keys) m3[key] = m1[key]
for (key in m2.keys) m3[key] = m2[key]
return m3
}
 
var base = { "name": "Rocket Skates" , "price": 12.75, "color": "yellow" }
var update = { "price": 15.25, "color": "red", "year": 1974 }
var merged = mergeMaps.call(base, update)
System.print(merged)
Output:
{name: Rocket Skates, color: red, price: 15.25, year: 1974}

zkl[edit]

base:=Dictionary(
"name", "Rocket Skates",
"price", 12.75,
"color", "yellow",);
update:=Dictionary(
"price", 15.25,
"color", "red",
"year", 1974,);
 
update.pump( new:=base.copy() );
 
new.pump(Void,fcn([(k,v)]){ println("%s\t%s".fmt(k,v)) });
Output:
price	15.25
color	red
year	1974
name	Rocket Skates