3. Dictionary Methods¶
Dictionaries have a number of useful built-in methods. The following table provides a summary and more details can be found in the Python Documentation.
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 |
The 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.
It is so common to iterate over the keys in a dictionary that you can omit the keys
method call in the for
loop — iterating over a dictionary implicitly iterates over its keys.
As we saw earlier with strings and lists, dictionary methods use dot notation, which specifies the name of the method to the right of the dot and the name of the object on which to apply the method immediately to the left of the dot. The empty parentheses in the case of keys
indicate that this method takes no parameters.
The 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.
Note that tuples (which will be discussed later in this chapter) are often useful for getting both the key and the value at the same time while you are looping. You can see an example of using the tuple in the first for
loop. The two loops do the same thing, the former just does it using a tuple.
The in
and not in
operators can test if a key is in the dictionary:
This operator can be very useful since looking up a non-existent key in a dictionary causes a runtime error.
The 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
).
Check your understanding
- cat
- key_list is a list of all the keys which is then sorted. cat would be at index 1.
- dog
- key_list is a list of all the keys which is then sorted. dog would be at index 2.
- elephant
- Yes, the list of keys is sorted and the item at index 3 is printed.
- bear
- key_list is a list of all the keys which is then sorted. bear would be at index 0.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
key_list = list(my_dict.keys())
key_list.sort()
print(key_list[3])
- 2
- get returns the value associated with a given key so this divides 12 by 6.
- 0.5
- 12 is divided by 6, not the other way around.
- bear
- Take another look at the example for get above. get returns the value associated with a given key.
- Error, divide is not a valid operation on dictionaries.
- The integer division operator is being used on the values returned from the get method, not on the dictionary.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
answer = my_dict.get("cat") // my_dict.get("dog")
print(answer)
- True
- Yes, dog is a key in the dictionary.
- False
- The in operator returns True if a key is in the dictionary, False otherwise.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
print("dog" in my_dict)
- True
- 23 is a value in the dictionary, not a key.
- False
- Yes, the in operator returns True if a key is in the dictionary, False otherwise.
What is printed by the following statements?
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
print(23 in my_dict)
- 18
- Add the values that have keys greater than 3, not equal to 3.
- 43
- Yes, the for statement iterates over the keys. It adds the values of the keys that have length greater than 3.
- 0
- This is the accumulator pattern. total starts at 0 but then changes as the iteration proceeds.
- 61
- Not all the values are added together. The if statement only chooses some of them.
What is printed by the following statements?
total = 0
my_dict = {"cat":12, "dog":6, "elephant":23, "bear":20}
for akey in my_dict:
if len(akey) > 3:
total = total + my_dict[akey]
print(total)