Show how to iterate over the key-value pairs of an associative array, and print each pair out.

Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.



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


 
x = <<>>;  // create an empty list
x.hello = 1;
x.world = 2;
x.["!"] = 3;
 
// to iterate over identifiers of a list one needs to use the function ''members''
// the identifiers are returned as a lexicographically ordered string row-vector
// here    ["!", "hello", "world"]
for(i in members(x)) 
{ printf("%s %g\n", i,  x.[i]); }
 
// occasionally one needs to check if there exists member of a list
y = members(x);  // y contains ["!", "hello", "world"]
clear(x.["!"]);  // remove member with identifier "!" from the list "x"
for(i in y) 
{ printf("%s %g\n", i,  x.[i]); }  // this produces error because x.["!"] does not exist
 
for(i in y) 
{ 
  if (exist(x.[i]))
  { printf("%s %g\n", i,  x.[i]); }  // we print a member of the list "x" only if it exists
}
 
 
 