Dictionaries
Written by Harnoor Chima (9/11/20)
Introduction
This lesson will cover how to use dictionaries in Python to store values that are assigned to keys. Dictionaries are very useful when you are trying to store a large amount of data in an organized manner.
Format
This format of a dictionary is fairly simple, you give it a name like a normal variable and then you open curly brackets where you will put keys and their corresponding values separated by a colon.
Accessing a Dictionary
To access individual values of specific keys inside a dictionary you write the name of the key in square brackets. We can use it in this example to find out what type of animal our pet is.
Changing Values
We can also change the values that are assigned to a specific key. So in this example we can say that the pet has aged by 3 years so we change the value for age accordingly.
Adding/Removing Items
We can also change a dictionary to include another key and value after it has already been created.
If we want to remove a key and value, we can do that by using the pop()
method and specifying the key name that we want to get rid of.
Looping Through a Dictionary
We can loop through a dictionary by using a for
loop to return the keys of a dictionary.
If we want to get all of the values from a dictionary we have to slightly modify our loop.
And finally, you can use the items()
method to loop through both the keys and the values.
Checking if a Key Exists in a Dictionary
We can use a simple if statement to find out if a specific key is contained within a dictionary.
Copying a Dictionary
Dictionaries can not simply be assigned to another variable, ex: dict1 = dict2
, because any changes made to dict1
will also be made to dict 2
. This is why, when we want to copy a dictionary we have to use the copy()
method.
Nested Dictionaries
We can use the concept of nested dictionaries to store many dictionaries inside of a single dictionary. This can be useful when we want to have multiple keys in our dictionary with multiple values.
Dictionary Constructor
We can use a function called dict()
to construct a dictionary for use using preset variables.
Conclusion
In this lesson, we learned how to use dictionaries to be able to store many values for just one key item. This will allow us to have more detailed indexes of a specific item. We also learned how to manipulate dictionaries by accessing or changing the contents within them.
Last updated