!!! Alert view looks like a list but is not of list type. Must be converted.
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 tofor akey in inventory:print("Got key", akey, "which maps to value", inventory[akey])
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()
for (k,v) in inventory.items():print("Got", k, "that maps to", v)### is equivalent tofor k in inventory:print("Got", k, "that maps to", inventory[k])
Prevent no key in dictionary
Hand-coded:
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")
Because dictionaries are mutable, you need to be aware of aliasing.
opposites ={'up':'down','right':'wrong','true':'false'}alias = oppositesprint(alias is opposites)alias['right']='left'print(alias is opposites)>>>True>>>True
Make copies instead
acopy = opposites.copy()acopy['right']='left'print(alias is opposites)>>>False
Sparse Matrices
A matrix is a two dimensional collection, typically thought of as having rows and columns of data:
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.