Merge (associative array)

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <map>
#include <string>
using namespace std;
 
map<string, int> a;
a["foo"] = 3;
a["bar"] = 4;
map<string, int> b;
a["baz"] = 2;
a["bar"] = 6;
 
map<string, int> c = a;
c.insert(b.begin(), b.end());
// c == {"bar": 6, "baz": 2, "foo": 3}

Java

import java.util.Map;
import java.util.HashMap;
 
Map<String, Integer> a = new HashMap<String, Integer>();
a.put("foo", 3);
a.put("bar", 4);
Map<String, Integer> b = new HashMap<String, Integer>();
a.put("baz", 2);
a.put("bar", 6);
 
Map<String, Integer> c = new HashMap<String, Integer>(a);
c.putAll(b);
// c == {"foo": 3, "bar": 6, "baz": 2}

JavaScript

jQuery

jquery

a = {'foo': 3, 'bar': 4}
b = {'baz': 2, 'bar': 6}
c = $.extend({}, a, b)
// c == {'baz': 2, 'foo': 3, 'bar': 6}

Objective-C

Modifying a mutable dictionary: developer.apple.com

- (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary
NSMutableDictionary *a = [NSMutableDictionary dictionaryWithObjectsAndKeys:@3, @"foo",
                                                                           @4, @"bar", nil];
NSMutableDictionary *b = [NSMutableDictionary dictionaryWithObjectsAndKeys:@2, @"baz",
                                                                           @6, @"bar", nil];
[a addEntriesFromDictionary::b];
// a == {@"foo": 3, @"bar": 6, @"baz": 2}

Perl

%a = ('foo' => 3, 'bar' => 4);
%b = ('baz' => 2, 'bar' => 6);
%c = (%a, %b);
# %c == ('foo' => 3, 'bar' => 6, 'baz' => 2)

alternately:

%a = ('foo' => 3, 'bar' => 4);
%b = ('baz' => 2, 'bar' => 6);
%c = %a;
@c{keys(%b)} = values(%b);
# %c == ('foo' => 3, 'bar' => 6, 'baz' => 2)

PHP

$a = array('foo' => 3, 'bar' => 4);
$b = array('baz' => 2, 'bar' => 6);
$c = array_merge($a, $b);
// $c == array('foo' => 3, 'bar' => 6, 'baz' => 2)
$c = $b + $a;
// $c == array('foo' => 3, 'bar' => 6, 'baz' => 2)
// note that "+" differs from array_merge() in that when there are duplicate entries
// it keeps the *first* one, while array_merge keeps the *last* one

Python

a = {'foo': 3, 'bar': 4}
b = {'baz': 2, 'bar': 6}
c = dict(a)
c.update(b)
# c == {'baz': 2, 'foo': 3, 'bar': 6}

alternately, use keyword arguments to update:

a = {'foo': 3, 'bar': 4}
b = {'baz': 2, 'bar': 6}
c = dict(a, **b)
# c == {'baz': 2, 'foo': 3, 'bar': 6}

Ruby

ruby-doc.org

hsh.merge(other_hash) => a_hash
hsh.merge(other_hash){|key, oldval, newval| block} => a_hash
a = {"foo" => 3, "bar" => 4}
b = {"baz" => 2, "bar" => 6}
c = a.merge(b)
# c == {"baz" => 2, "foo" => 3, "bar" => 6}
Personal tools