Python - Using dictionaries for sparse data structures: Tuple keys

Introduction

Dictionary keys are commonly way to implement sparse data structures.

For example, multidimensional arrays where only a few positions have values stored in them:

Demo

Matrix = {} 
Matrix[(2, 3, 4)] = 88 # from   w  ww  .  jav a2 s . co  m
Matrix[(7, 8, 9)] = 99 

X = 2; Y = 3; Z = 4           # ; separates statements: see Chapter 10 
print( Matrix[(X, Y, Z)] )
print( Matrix )

Result

Here, we've used a dictionary to represent a three-dimensional array that is empty except for the two positions (2,3,4) and (7,8,9).

The keys are tuples that record the coordinates of nonempty slots.

Related Topic