Returns a view of the key-value pairs in the dictionary. It is (key, value) tuple.
get
key
Returns the value associated with key; None otherwise
get
key,alt
Returns the value associated with key; alt otherwise
!!! 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 to
for 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 to
for 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")
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 .