Dictionaries
- 03:02
How dictonaries are used in Python, how they are structures, and how to represent and manipulate data using dictionaries.
Downloads
No associated resources to download.
Glossary
dictionary PythonTranscript
In Python, we use dictionaries to organize other objects, but they're a little bit more complex than the list or the set. In the real world, a dictionary contains pairs of words and definitions. In Python, we call the word the key, and the definition the value. So a dictionary is a collection of key value pairs, and each one of those key value pairs is called an item.
If you're thinking about this in Excel, a dictionary could be visualized as a table with two columns. On the left, we have the key, and on the right we have the value. So again, in a dictionary, the key is kind of like the word and the value is kind of like the definition of the word. Let's take a look at what that looks like in Python.
So here is a dictionary in Python. It looks similar to the table that we just saw in Excel. You have your keys on the left and your values on the right. Don't be confused here. Dictionaries are like sets in the sense that they are enclosed by these curly braces. Don't get confused by that Python knows that this is a dictionary because of the formatting of the objects inside those curly braces, which are these items, these key value pairs. Here we have a descriptive string on the left and then a colon separating the key from the value and the value on the right, which in this case is a float type object. In this course, we're primarily going to use descriptive strings for our keys in dictionaries, and you can use any type of object for the value on the right, including other dictionaries. Don't forget to separate these by a colon and to put a comma at the end of each item.
Well, what if you wanted to include more data in your dictionary? For example, if you wanted to add the name of the company in addition to its beta value inside your dictionary? Well, in Excel, we would represent that by splitting our value into two columns. So here we have the key on the left, which is the ticker of our company in one column, and the value is split into two columns containing the name of the company and the beta value of the company.
Putting the same data into the dictionary in Python looks very, very similar. So you have your key on the left, this the ticker of the company. And on the right we've just created lists as our values. So we have a list of two objects, the name of the company, which is a string, and the beta value of the company, which is a float. So our keys on the left are strings, and our values in this dictionary are just lists containing two objects, just like the two columns that you saw in Excel.