12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Here, it looks as if D is a 100-item list, but it’s really a dictionary with a single entry;the value of the key 99 is the string 'spam'. You can access this structure with offsetsmuch like a list, but you don’t have to allocate space for all the positions you mightever need to assign values to in the future. When used like this, dictionaries are likemore flexible equivalents of lists.Using dictionaries for sparse data structuresIn a similar way, dictionary keys are also commonly leveraged to implement sparsedata structures—for example, multidimensional arrays where only a few positionshave values stored in them:>>> Matrix = {}>>> Matrix[(2, 3, 4)] = 88>>> Matrix[(7, 8, 9)] = 99>>>>>> X = 2; Y = 3; Z = 4 # ; separates statements>>> Matrix[(X, Y, Z)]88>>> Matrix{(2, 3, 4): 88, (7, 8, 9): 99}Here, we’ve used a dictionary to represent a three-dimensional array that is emptyexcept for the two positions (2,3,4) and (7,8,9). The keys are tuples that record thecoordinates of nonempty slots. Rather than allocating a large and mostly emptythree-dimensional matrix, we can use a simple two-item dictionary. In this scheme,accessing an empty slot triggers a nonexistent key exception, as these slots are notphysically stored:>>> Matrix[(2,3,6)]Traceback (most recent call last):File "", line 1, in ?KeyError: (2, 3, 6)Avoiding missing-key errorsErrors for nonexistent key fetches are common in sparse matrixes, but you probablywon’t want them to shut down your program. There are at least three ways to fill in adefault value instead of getting such an error message—you can test for keys aheadof time in if statements, use a try statement to catch and recover from the exceptionexplicitly, or simply use the dictionary get method shown earlier to provide adefault for keys that do not exist:>>> if Matrix.has_key((2,3,6)): # Check for key before fetch... print Matrix[(2,3,6)]... else:... print 0...0Dictionaries in Action | 167

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

Saved successfully!

Ooh no, something went wrong!