Associative array/Creation: Difference between revisions

Line 4,443:
echo "Key: $key Value: $value";
}</lang>
 
=={{header|Picat}}==
Associative arrays are called "map" in Picat.
<lang Picat>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.
</lang>
 
Output:
<pre>(map)[]
(map)[a = 1,picat = 3,[a,list,of,different,things,[including,lists],3.14159] = 2]
a = 1
b = default value
(map)[b = 2,a = 1,e = 5,h = 8,f = 6,g = 7,d = 4,c = 3]
h = 8
no key 'z'
keys = abcdefgh
values = [1,2,3,4,5,6,7,8]
bdfh</pre>
 
=={{header|PicoLisp}}==
495

edits