15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

352<br />

Using Dictionaries<br />

Using Dictionaries<br />

Essentially, a dictionary is like a collection but with two additional advantages:<br />

✦ Searching <strong>for</strong> that data in a dictionary is much faster.<br />

Dictionaries use a data structure known as a hash table (which you read<br />

more about later in this chapter). Every item stored in a dictionary must<br />

include a unique key.<br />

Collections don’t require keys because searching <strong>for</strong> data in a collection<br />

is sequential. There<strong>for</strong>e, the computer must start at the beginning of the<br />

collection and examine each item one by one to retrieve a specific item.<br />

The more items in a collection, the slower the search process.<br />

If a <strong>programming</strong> language offers collections, it usually also offers dictionaries.<br />

If a <strong>programming</strong> language doesn’t offer collections, it probably<br />

doesn’t offer dictionaries either.<br />

✦ In a dictionary, the key can be any value, including strings or numbers,<br />

which gives you greater flexibility in assigning keys to data.<br />

If a collection uses a key to identify data, that key must be a string.<br />

Dictionaries are also called associative arrays. When you store data and a<br />

key, that’s known as a key-value pair (refer to Figure 3-5).<br />

Like a collection, a dictionary is a data type, so you must first declare a variable<br />

as a dictionary. Then you must create a new dictionary and store data<br />

in that dictionary.<br />

To create a dictionary in the Smalltalk <strong>programming</strong> language, you could use<br />

the following:<br />

blackbook := Dictionary new.<br />

This code declares the blackbook variable as a dictionary data type. The<br />

new command simply creates an empty dictionary.<br />

Adding data to a dictionary<br />

After you declare a variable as a dictionary data type, you can start<br />

adding data to that dictionary by defining both the data and the key you<br />

want to associate with that date. So if you want to add the name Dick Ross<br />

to a dictionary and assign it a moron key, you could use the following:<br />

blackbook := Dictionary new.<br />

blackbook at: ‘moron’ put: ‘Dick Ross’.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!