Key Concepts

Review core concepts you need to learn to master this subject

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".

Creating Dictionaries
Lesson 1 of 2
  1. 1
    A 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…
  2. 2
    In 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…
  3. 3
    We 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…
  4. 4
    A 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:…
  5. 5
    To add a single key: value pair to a dictionary, we can use the syntax: dictionary[key] = value For example, if we had our menu dictionary from the first exercise: menu = {“oatmeal”: 3, “avocad…
  6. 6
    If 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…
  7. 7
    We know that we can add a key by using the following syntax: menu[“banana”] = 3 This will create a key “banana” and set its value to 3. But what if we used a key that already has an entry in the…
  8. 8
    Let’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…
  9. 9
    So far we have learned: - How to create a dictionary - How to add elements to a dictionary - How to update elements in a dictionary - How to use a dict comprehension to create a dictionary from two…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo