Dictionaries
Learn all about the Python dictionary structure and how to create and use key-value pairs in your code.
StartKey Concepts
Review core concepts you need to learn to master this subject
Accessing and writing data in a Python dictionary
Syntax of the Python dictionary
Merging Dictionaries with the .update()
Method in Python
Dictionary value types
Python dictionaries
Dictionary accession methods
get() Method for Dictionary
The .pop()
Method for Dictionaries in Python
Accessing and writing data in a Python dictionary
Accessing and writing data in a Python dictionary
my_dictionary = {"song": "Estranged", "artist": "Guns N' Roses"}
print(my_dictionary["song"])
my_dictionary["song"] = "Paradise City"
Values in a Python dictionary can be accessed by placing the key within square brackets next to the dictionary. Values can be written by placing key within square brackets next to the dictionary and using the assignment operator (=
). If the key already exists, the old value will be overwritten. Attempting to access a value with a key that does not exist will cause a KeyError
.
To illustrate this review card, the second line of the example code block shows the way to access the value using the key "song"
. The third line of the code block overwrites the value that corresponds to the key "song"
.
- 1A dictionary is an unordered set of key: value pairs. It provides us with a way to map pieces of data to each other so that we can quickly find values that are associated with one another. Sup…
- 2In the previous exercise, we saw a dictionary that maps strings to numbers (i.e., “avocado toast”: 6). However, the keys can be numbers as well. For example, if we were mapping restaurant bill su…
- 3We can have a list or a dictionary as a value of an item in a dictionary, but we cannot use these data types as keys of the dictionary. If we try to, we will get a TypeError. For example: powe…
- 4A dictionary doesn’t have to contain anything. Sometimes we need to create an empty dictionary when we plan to fill it later based on some other input. We can create an empty dictionary like this:…
- 6If we wanted to add multiple key : value pairs to a dictionary at once, we can use the .update() method. Looking at our sensors object from a previous exercise: sensors = {“living room”: 21, “kit…
- 7We know that we can add a key by using syntax like: menu[“avocado toast”] = 7 This will create a key “avocado toast” and set the value to 7. But what if we already have an ‘avocado toast’ entry …
- 8Let’s say we have two lists that we want to combine into a dictionary, like a list of students and a list of their heights, in inches: names = [‘Jenny’, ‘Alexus’, ‘Sam’, ‘Grace’] heights = [61, 70…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory