Open oldoc63 opened 1 year ago
Once you have a dictionary, you can access the values in it by providing the key.
If a key does not exist, python will throw a KeyError
One way to avoid the KeyError is to first check if the key exist in the dictionary.
This will not throw an error, because key_to_check in building_heights will return False, and so we never try to access the key.
When we try to access a key that doesn't exist, the program will go into the except block and print "That key doesn't exist!".
Dictionaries have a .get() method to search for a value instead of the my_dict[key]. If the key you are trying to .get() does not exist, it will return None by default:
You can also specify a value to return if the key doesn't exist.
Sometimes we want to get a key removed from the dictionary. We can use .pop() to do this. Just like with .get(), we can provide a default value to return if the key does not exist.
.pop() works to delete items from a dictionary, when you know the key value.
Sometimes we want to operate on all keys in a dictionary. We can get a roster of the keys without including the values using the built-in list function:
Dictionaries also have a .keys() method that returns a dict_keys object (view) which provides a look at the current state of the dictionary, without the user being able to modify anything. The dict_keys object returned by .keys() is a set of the keys in the dictionary. You cannot add or remove elements from a dict_keys object, but it can be used in the place of a list for iteration:
Dictionaries have a .values() method that returns a dict_values object with all the values in the dictionary. Similarly, it can be used in the place of a list for iteration.
There is no built-in function to get all of the values as a list, for most purposes, the dict_values object will act that way, but if you really want to have a list, you can use:
You can get both the keys and the values with the .items() method. Like .keys() and .values(), it returns a dict_list object. Each element of the dict_list returned by .items() is a tuple consisting of (key, value).
We'll learn to: