Dictionary

Inherits from: Object
Instance variables: table, size

A mutable collection of key-value pairs with hashed lookup. Keys can be any object that responds to hash and =; symbols and strings are the most common key types.

Create dictionaries with the literal syntax #{key -> value} or incrementally with Dictionary new and at:put:. Pairs in the literal are separated by periods; keys and values can be any expression.

Core operations (at:, at:put:, includesKey:, size, keys, values, do:, keysAndValuesDo:, removeKey:) are implemented as VM primitives. This file adds convenience methods on top.

Test
Dictionary new size >>> 0
Dictionary new isEmpty >>> true
#{#x -> 1. #y -> 2} size >>> 2
(#{#name -> 'Alice'} at: #name) >>> 'Alice'
Example
"Dictionary literal syntax"
| d <Dictionary> |
d := #{#name -> 'Alice'. #age -> 30. #active -> true}.
d at: #name
Example
"Build a dictionary with cascaded puts"
| d <Dictionary> |
d := Dictionary new.
d at: #name put: 'Alice'.
d at: #age put: 30.
d size

Class Methods

primitives

class new

Create a new empty dictionary.

Instance Methods

primitives

at:

Return the value associated with key, or nil if not present.

at:ifAbsent:

Return the value at key, or evaluate block if absent.

at:ifPresent:

If key exists, evaluate block with its value; otherwise return nil.

at:put:

Associate value with key. Returns value.

do:

Evaluate block once for each value.

includesKey:

Return true if the dictionary contains key.

isEmpty

Return true if the dictionary has no entries.

keys

Return an array of all keys.

keysAndValuesDo:

Evaluate block with each key-value pair.

removeKey:

Remove the entry for key. Raises an error if absent.

removeKey:ifAbsent:

Remove the entry for key; if absent, evaluate block.

size

Return the number of entries.

values

Return an array of all values.

uncategorized

at:ifAbsentPut:

Return the value at key. If the key is absent, evaluate block, store the result under key, and return it.

Test
d := Dictionary new.
d at: #x ifAbsentPut: [42] >>> 42
d at: #x >>> 42
d at: #x ifAbsentPut: [99] >>> 42
copy

Return a shallow copy of the dictionary. The new dictionary has the same keys and values but is a distinct object.

Test
d := Dictionary new.
d at: #x put: 1.
c := d copy.
c at: #x >>> 1
c size >>> 1
keysDo:

Evaluate block once for each key in the dictionary.

Test
d := Dictionary new.
d at: #a put: 1.
d keys size >>> 1
notEmpty

Return true if the dictionary contains at least one entry.

Test
d := Dictionary new.
d notEmpty >>> false
d at: #x put: 1.
d notEmpty >>> true
printString

Return a human-readable string representation of the dictionary.

Test
Dictionary new printString >>> 'Dictionary()'
yourself

Return the receiver. Useful at the end of a cascade to return the dictionary itself rather than the last message result.

Test
Dictionary new yourself class >>> #Dictionary