Dictionary Functions
- 03:14
Learn how to manipulate dictionaries in Python, including accessing keys, values, and items, adding new items, updating values, and removing items from a dictionary.
Downloads
No associated resources to download.
Glossary
dictionary PythonTranscript
Once you have a dictionary, you can create an output with the keys within the dictionary, the values in the dictionary, or all of the items in your dictionary. And this is useful when you wanna write a piece of code that iterates through the keys values or the items in your dictionary to perform a certain task. So the way that you would do that is you first type the name of the dictionary. So here we have our healthcare beta values.
And to access the keys, I simply type dot keys, and then open and close parentheses. And now I have all my keys in the dictionary. Similarly, if I wanna see the values, I use the values function in the same format.
And if I wanna see all of the items, I just use dot items and it gives me all of the key value pairs in my dictionary. What if you have a dictionary and you want to add a new item to that dictionary? It's really easy to do. First you type the name of your dictionary. So here, healthcare beta values.
And let's say that I want to add the beta value for pharmaceutical company Merck. So first I'm gonna do open square bracket, and I'm gonna write the key that I want to use for this item. So I'm gonna use Merck's ticker, MRK, and then similarly to how I would define a variable, I just use the equals sign and then the value that I want to be assigned to that key within my dictionary. So in this case, I'm gonna use a beta of 0.65.
So now that item has been created in my dictionary, healthcare beta values. And I can show you by calling the keys in that dictionary using the keys function. And you can see that Merck has been added. That ticker for Merck has been added to the end of my list of keys. And if I call that item, then I'm gonna get that beta value of 0.65.
Updating the value of an item in your dictionary is identical to creating a new one, except you use an existing key instead of a new key. So if I wanna update that beta value for Merck from 0.65 to 0.71, I would just refer to that key MRK, and then use the equal sign to assign a new value. So here I'm gonna do 0.71, and now when I call it again, you can see that it has a new value. If I wat to remove an item, I use the DEL Dell short for delete function.
So now I've deleted the item for JNJ, Johnson and Johnson, and if I print the keys, you can see that that item has been removed from my dictionary.