Dictionaries
1. Python dictionaries
In this lesson, you are going to learn about a highly versatile Python data structure called a "dictionary".2. What is a dictionary?
Python dictionaries are data structures similar to a MATLAB "structure array." They are a collection of key:value pairs. For each unique key stored in the dictionary, there is a value associated with it. Unlike NumPy arrays and lists, however, there is no guarantee that the order of items in the dictionary will be maintained. Let's get a better sense of what dictionaries are by learning how to create, query, and modify them.3. Retrieving data from a dictionary
Here, we have a dictionary called "definitions," which contains definitions for various English words. The words are the keys of the dictionary, and the definitions are the values. We can retrieve the definition of the word "aardvark" by passing it in as the key of the dictionary, using the square brackets. In this case, the value is a long string containing the definition of the word "aardvark."4. Creating dictionaries
Just like we used square brackets to create lists, we use curly brackets to create dictionaries. A key:value pair is denoted by the key, followed by a colon, then the value for that key. Each key:value pair in the dictionary is separated by a comma.5. Adding data to a dictionary
Once created, dictionaries can be modified. We can add a new key:value pairs to the dictionary by assigning the value to the dictionary's key, like so. Note, that values can be anything — strings, numbers, lists, even other dictionaries. Oops. It looks like we made a typo. Toby isn't a five hundred pound dog. Let's see how to fix that.6. Updating dictionaries
We can update values in the same way that we added them: by assigning the new value to the entry in the dictionary. Here, we assign a new weight, 52.3 lbs, to the key "weight (lbs)" in the dictionary "dog." Let's print it to make sure it worked. That's better.7. Removing data from a dictionary
We can also remove key:value pairs from a dictionary. To do so, we simply pass the key we want to remove to the .pop() method. Here, we are removing the key "birthdate," and it's value from the dictionary.8. Let's practice!
Great! Dictionaries are a very powerful data structure in Python. Now that you've learned the basics of the Python dictionary, you're ready to practice.Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.