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


include ..\Utilitys.pmt
 
def getd    /# dict key -- dict data #/
    swap 1 get rot find nip
    dup if
        swap 2 get rot get nip
    else
        drop "Unfound"
    endif
enddef
 
 
def setd    /# dict ( key data ) -- dict #/
    1 get var ikey
    2 get var idata
    drop
    1 get ikey find var p drop
    p if
        2 get idata p set 2 set
    else
        2 get idata 0 put 2 set
        1 get ikey 0 put 1 set
    endif
enddef
 
 
def pair    /# dict n -- dict ( k d ) #/
    1 over 2 tolist var ikey
    2 swap 2 tolist var idata
    ikey sget
    swap idata sget rot swap
    2 tolist
enddef
 
def scandict    /# dict n -- dict ( ) #/
    var n
    1 get len nip
    for
        pair
        n if n get nip endif
        print nl
    endfor
enddef
 
def pairs   /# dict -- dict ( ) #/
    0 scandict  
enddef
 
def keys
    1 scandict  
enddef
 
def values
    2 scandict  
enddef
 
/# ---------- MAIN ---------- #/
 
( ( ) ( ) )
 
( "one" 1 ) setd
( 2 "duo" ) setd
( ( 3 4 ) ( 5 "six" ) ) setd
 
pairs nl
keys nl
values
 