This language bar is your friend. Select your favorite languages!

Idiom #8 Initialize a new map (associative array)

Declare a new map object x, and provide some (key, value) pairs as initial content.

1
use std::collections::BTreeMap;
let mut x = BTreeMap::new();
x.insert("one", 1);
x.insert("two", 2);
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;

use Ada.Containers;
declare
   package Maps is new Indefinite_Hashed_Maps (Key_Type => String,
                                               Element_Type => Integer,
                                               Hash => Ada.Strings.Hash,
                                               Equivalent_Keys => "=");
      
   use Maps;
      
   X : Map := Empty_Map;
begin
   X.Insert ("One", 1);
   X.Insert ("Two", 2);
   X.Insert ("Three", 3);
end;
#include <map>
std::map<const char*, int> x;
x["one"] = 1;
x["two"] = 2;
System.Collections.Generic
Dictionary<int, string> x = new Dictionary<int, string>()
{
    (1, "Value1"),
    (2, "Value2")
};
int[string] x = ["one": 1, "two": 2];
var x = {
	"one": 1,
	"two": 2
};
x = %{"one" => 1, "two" => 2}
1
X = #{one => 1, "two" => 2.0, <<"three">> => [i, i, i]}.
x := map[string]int {"one" : 1, "two" : 2}
x = Data.Map.Strict.fromList [ ("red", "FF0000"), ("blue", "0000FF") ]

var x = {"one": 1, "two":2}
import java.util.Map;
import java.util.HashMap;
Map<String,Integer> x = new HashMap<>();
x.put("one", 1);
x.put("two", 2);
x = {one = 1, two = 2}
$x = array( "one"=>1, "two"=>2 );
uses fgl;
type TMap = specialize TFPGMap<String, Integer>;
var x: TMap;

begin
  x := TMap.Create;
  x['one'] := 1;
  x['two'] := 2;  
end.
my %map = ( 
    name=>'Roboticus',
    "foo bar"=>"joe"
);
x = {"one" : 1, "two" : 2}
x = {one: 1, two: 2}
val x = Map("a" -> 1, "b" -> 2, "c" -> 3)
(define x '(
    ("one" 1) 
    ("two" 2) 
    ("three" 3)))

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms