!!! Alert view looks like a list but is not of list type. Must be converted.
Skipping .keys()
It is used so often, it got implemented as default looping, and for loop iterating over a dictionary implicitly iterates over its keys.
.keys() vs .items()
Prevent no key in dictionary
Hand-coded:
Built-in way:
Aliasing and Copying
Because dictionaries are mutable, you need to be aware of aliasing.
Make copies instead
Sparse Matrices
A matrix is a two dimensional collection, typically thought of as having rows and columns of data:
sparse matrix
Represented in code as:
But the awful amount of zeros is making it really inefficient. In fact, only three of the data values are nonzero. This type of matrix has a special name. It is called a sparse matrix.
An alternative representation is to use a dictionary.
Access data with the default value assigned:
To display the matrix of size n:m loop the range, asking for each key.
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
for akey in inventory.keys():
print("Got key", akey, "which maps to value", inventory[akey])
>>> Got key apples which maps to value 430
>>> Got key bananas which maps to value 312
>>> Got key oranges which maps to value 525
>>> Got key pears which maps to value 217
for akey in inventory.keys():
print("Got key", akey, "which maps to value", inventory[akey])
### is equivalent to
for akey in inventory:
print("Got key", akey, "which maps to value", inventory[akey])
for (k,v) in inventory.items():
print("Got", k, "that maps to", v)
### is equivalent to
for k in inventory:
print("Got", k, "that maps to", inventory[k])
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
print('apples' in inventory)
print('cherries' in inventory)
if 'bananas' in inventory:
print(inventory['bananas'])
else:
print("We have no bananas")