Note 15.8.2.
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
http://docs.python.org/py3k/library/stdtypes.html#mapping-types-dict
Method | Parameters | Description |
---|---|---|
keys | none | Returns a view of the keys in the dictionary |
values | none | Returns a view of the values in the dictionary |
items | none | Returns a view of the key-value pairs in the dictionary |
get | key | Returns the value associated with key; None otherwise |
get | key,alt | Returns the value associated with key; alt otherwise |
keys
method returns what Python 3 calls a view of its underlying keys. We can iterate over the view or turn the view into a list by using the list
conversion function.keys
method call in the for
loop — iterating over a dictionary implicitly iterates over its keys.keys
indicate that this method takes no parameters.values
and items
methods are similar to keys
. They return view objects which can be turned into lists or iterated over directly. Note that the items are shown as tuples containing the key and the associated value.get
method allows us to access the value associated with a key, similar to the [ ]
operator. The important difference is that get
will not cause a runtime error if the key is not present. It will instead return None. There exists a variation of get
that allows a second parameter that serves as an alternative return value in the case where the key is not present. This can be seen in the final example below. In this case, since “cherries” is not a key, return 0 (instead of None).mydict = {"cat":12, "dog":6, "elephant":23, "bear":20}
keylist = list(mydict.keys())
keylist.sort()
print(keylist[3])
mydict = {"cat":12, "dog":6, "elephant":23, "bear":20}
answer = mydict.get("cat") // mydict.get("dog")
print(answer)
mydict = {"cat":12, "dog":6, "elephant":23, "bear":20}
print("dog" in mydict)
mydict = {"cat":12, "dog":6, "elephant":23, "bear":20}
print(23 in mydict)
total = 0
mydict = {"cat":12, "dog":6, "elephant":23, "bear":20}
for akey in mydict:
if len(akey) > 3:
total = total + mydict[akey]
print(total)