76
❘
CHAPTER 4
Using ArrAys And ColleCtions
Adding new members to a dictionary is easy. You simply provide a new key and assign a value to it,
as shown in the code. If you want to verify that a particular key appears in the dictionary, simply
use the
has_key()
method. It’s important to remember that dictionaries use methods different from
those of other storage techniques. For example, there’s no
append()
method when working with a
dictionary. Interestingly enough, a dictionary does provide the
pop()
method.
Iterating through a dictionary (listing its content) is also a bit different. You still use a
for
loop to
perform the task. However, notice that you use the
iteritems()
method to obtain a list of key/
value pairs from the dictionary. Figure 4-12 shows the output from this example.
FIguRE 4-12:
Dictionaries are best used for named data.
uSINg IRoNPyTHoN CoNSTRuCTIvEly
One of the most important facts that you can take away from this chapter is that there are many ways
to store and manage data in memory. You could probably use arrays for absolutely every data storage
need, but doing so would be painful from a development perspective. Not every problem is easy to solve
using just an array, so you also need collections and dictionaries. In fact, most languages support other
data storage mechanisms — only IronPython could successfully use these three methods to meet most
needs. As mentioned in Chapter 1, IronPython tends to simplify things and so far you’ve seen a number
of examples of that strategy in the book.
It’s time to look at the memory storage methodologies in IronPython. If you’ve been working with
another language for a long time (and I’m assuming that you have), it’s probably going to take a
while to get used to the IronPython method of doing things. You should take time now to work
through the examples in the chapter and then create a few of your own. The question you need to
ask is how the data storage structures in IronPython relate to those used in the language you already
know. In many cases, making this comparison can help you become productive considerably faster.
In addition, this exercise will firmly implant the IronPython methodology in your brain.
Chapter 5 is the last of the basics chapters in the book. In this case, you discover how to interact
with objects. This means looking at objects that IronPython already provides, as well as creating
new objects of your own. Up to this point, you could probably look at IronPython as you would any
other scripting language. However, Chapter 5 starts to show you some of the impressive capabilities
that IronPython provides. Of course, Chapter 5 will build on what you’ve learned so far — all the
basics in Chapters 1 through 4 will come into play as you begin working with objects.
548592c04.indd 76
2/24/10 12:47:38 PM
www.finebook.ir
Do'stlaringiz bilan baham: |