oldoc63 / learningDS

Learning DS with Codecademy and Books
0 stars 0 forks source link

Using Dictionaries #352

Open oldoc63 opened 1 year ago

oldoc63 commented 1 year ago

We'll learn to:

oldoc63 commented 1 year ago

Get a key

Once you have a dictionary, you can access the values in it by providing the key.

oldoc63 commented 1 year ago

Get an Invalid Key

If a key does not exist, python will throw a KeyError

oldoc63 commented 1 year ago

To avoid KeyError first check

One way to avoid the KeyError is to first check if the key exist in the dictionary.

oldoc63 commented 1 year ago

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.

oldoc63 commented 1 year ago

Try/Except to get a 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!".

oldoc63 commented 1 year ago

Safely Get a Key

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:

oldoc63 commented 1 year ago

Specify a value if the key doesn't exist

You can also specify a value to return if the key doesn't exist.

oldoc63 commented 1 year ago

Delete a Key

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.

oldoc63 commented 1 year ago

.pop() works to delete items from a dictionary, when you know the key value.

oldoc63 commented 1 year ago

Get All Keys

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:

oldoc63 commented 1 year ago

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:

oldoc63 commented 1 year ago

Get All Values

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.

oldoc63 commented 1 year ago

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:

oldoc63 commented 1 year ago

Get All Items

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).