A Dictionary
is a collection of Association
s. It is, in fact, Smalltalk's canonical collection of Associations. (An instance of the Association Class is a key value pair, where the value can be an object of any Class).
The advantage a Dictionary gives you is that it has specialised methods for dealing with Associations, compared to other Collections you might be tempted to use.
A Dictionary
provides:
removeKey: aKey .
removes aKey
includesKey: aKey .
checks for the existence of the key
includes: aValue .
checks for the existence of a value
at:put: .
shorthand for
anAssociation := Association key:value: .
aDictionary add:
e.g.
anAssociation := Association key: 'Hello'
value: 'A greeting people often use' .
aDictionary add: anAssociation .
If the key already exists in the Dictionary, then at:put
will overwrite the pre-existing value with the new value, so it's important to check and make sure that the key has a unique value when adding new items.
Both the key and the value can be an object instance of any Class. Every Association in a Dictionary can be any kind of object, and every single key and value might be a instance of a different Class of object from every other element in the Dictionary.
You can create an Association by
anAssociation := Association key: 'keyOfElement' value: 'valueOfElement'
or, more succinctly,
anAssociation := 'keyOfElement' -> 'valueOfElement'
If you want to use keys entirely made specifically of Symbol
s, there is also the Class
IdentityDictionary
{ } asDictionary
is not supported in Squeak, Dolphin Smalltalk or Amber. It is a Pharo-specific convenience syntax, and works from at least Pharo 1.4 upwards. – Wig