Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


go =>
 
   % Create an empty map
   Map = new_map(),
   println(Map),
 
   % add some data
   Map.put(a,1),
   Map.put("picat",2),
   Map.put("picat",3), % overwrite values
   % Add a new value (a long list of different stuff)
   Map.put([a,list,of,different,"things",[including, lists],3.14159],2),
   println(Map),
 
   println(a=Map.get(a)), % get a value
   println(b=Map.get(b,'default value')), % the second argument to get/2 is the default value
 
   % create a map from a list of values
   Map2 = new_map([K=V : {K,V} in zip([a,b,c,d,e,f,g,h],1..8)]),
   println(Map2),
   println(h=Map2.get(h)),
 
   % Check if there is a value in the map
   if not Map2.has_key(z) then
     println("no key 'z'")
   end,
 
   % keys() and value() returns unsorted list of elements
   % so we sort them.
   println(keys=Map2.keys().sort()),
   println(values=Map2.values().sort()),
 
   % Print the values for the keys that are even
   println([K : K=V in Map2, V mod 2=0].sort), 
 
   nl.
 