Expand/Shrink

pop_dict

Definition: object {key,data} = pop_dict(integer tid=1, bool rev=false)
-- or --
object {key,data} = peep_dict(integer tid=1, bool rev=false)
Description: Retrieves the lowest (or highest if rev is true) {key,data} in the specified dictionary and in the case of pop_dict deletes it.
pwa/p2js: Supported.
Comments: tid can be omitted, to use the default dictionary, or the result of a previous new_dict() call.

If the dictionary is empty, returns the default of NULL or as overidden by setd_default().
Obviously, overidding the default with a suitable 2-element sequence can prevent some crashes when trying to subscript or directly assign the key and data from the result, and/or reduce the need for potentially fiddly tests on it or having to check that dict_size() is not zero first.

There is no push_dict() routine, rather setd() will add an entry to the dictionary, not at the end of a "queue", but instead at the appropriate location in the dictionary index according to the specified key. For a true (in-order-of-addition) queue or stack, simply use a standard Phix sequence, and invoke append()/prepend() to push items, and slice off the same/other end to pop them, depending on the fifo/filo/lifo/lilo type of queue/stack needed.

In many cases, a priority queue can be much faster, however there is no (sensible) way as yet to tell whether or not said queue already contains a specific key/priority (it would have to perform a near-full traversal).
Example:
setd_default({NULL,NULL},mydict)
-- for ... (say)
    if getd_index(key,mydict)=NULL then -- (optional)
        setd(key,data,mydict)
    end if
-- end for
-- ...
-- while ... (say)
    object {key,data} = pop_dict(mydict)
    if key=NULL then exit end if -- mydict empty
-- end while

The getd_index() check shown can avoid some unnecessary re-balancing checks, and hence if there is a reasonably high probability that a key already exists, and assuming that if it does either there is no need or you don’t want to update the data, then it can be noticeably faster. Conversely if there is a fairly low probability that a key already exists, it can prove quite a bit slower.

Typically of course there is some kind of loop involved around such calls, it could be the same one.
See Also: new_dict, setd, setd_default, getd, getd_index, deld, dict_size, pqueue