The course is part of this learning path
In this course, we explore Dictionaries in Python. This course is part of a series of content designed to help you learn to program with the Python programming language.
- Describe the syntax for creating dictionaries
- Describe the syntax for accessing a value
- Describe how to delete a key-value pair
- Describe how to merge two dictionaries
This course was designed for first-time developers wanting to learn Python.
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language.
Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: firstname.lastname@example.org. And one of our cloud experts will reply.
In this lesson we’ll explore Python’s built-in dictionary object type a bit closer. We’ll cover the ways to create and use dictionaries. Dictionary objects are a container for storing key-value pairs of objects. Let’s dive into what it means to be a key-value pair.
A key-value pair consists of two related objects. Where the key identifies the value. For example:
- The key name could reference a value of Python.
- The key initial_release_date could reference a value of February 20th, 1991.
- The key 42 could be an ID which references some other object.
The concept of key-value pairs is a recurring theme in computer science. Key-value pairs are extremely versatile because so many concepts can be conveyed in terms of key-value pairs. In fact, as an example of how common this concept is, we can think of name bindings as a type of key value pair. We have the name which is a key and the bound object is the value.
Dictionary objects are used to store multiple key-value pairs. Which is what makes them interesting. Because each individual key-value pair can describe one aspect of the overall data being stored. For example if we were to use a dictionary to store attributes of a cat, we could include a key called name with a value of Ada. And another key called age with a value of 3.
This example is contrived. However, hopefully it illustrates the point. Which is: Dictionary objects are designed to store a collection of related key-value pairs. Using dictionaries in Python is very common across a wide range of problem domains. It’s a highly foundational object in Python. Which is why they’re incorporated into the Python language syntax.
Python provides a built-in function for creating a new dictionary. When this function is called without providing any arguments it creates an empty dictionary object. And while it exists, it’s more common to use the shorthand syntax. This shorthand syntax is considered to be more idiomatic - or Pythonic.
The syntax for creating a dictionary is to use curly brackets. For an empty dictionary you use an open and close curly bracket. You can also create a dictionary with initial values. The syntax for defining a key-value pair inside a dictionary is to separate the key and value using a colon.
Let’s focus on this syntax for a moment. Notice we have a single pair of curly brackets. And inside we have two key-value pairs. Each pair is separated by a comma. And each key-and-value is separated using a colon. Using this pattern, you can add as many key-value pairs as you’d like. Just repeat this pattern for each new pair.
In this example both keys are string objects. However, the objects used for values are different from each other. Python doesn’t impose limitations on the object type used for values. A dictionary’s value can be absolutely any object in the entire Python runtime. Making dictionaries the ultimate cubby storage system! Because they can store anything!
Keys are a different story. Keys are required to be hashable. What does it mean to be hashable? That’s a really fun question to answer. However, we’re not going to get distracted by exactly what that means, right now. Just know that there are limitations for keys. However, many common object types such as strings and numbers are valid. Which should be more than enough at this stage in your Python journey.
Once you create a dictionary object you can interact with it in different ways. Depending on if you want to operate on an individual value or on the entire dictionary. There are different methods and operators used for individual vs dictionary operations.
Let’s start by learning how to interact with individual key-value pairs. And then we’ll review the dictionary based operators. Let’s begin with an empty dictionary. We’ll bind the name cat to the dictionary object created by this syntax.
In order to interact with specific values we reference them by key. The syntax for referencing a value by its key is to use square brackets. This is similar to how a list is accessed by its index.
Inside the square brackets we can include the key. This uses a string of: name as the key for a value of Ada. This first part is the syntax for referencing a dictionary value with its key. This becomes a stand-in for the value object. This is similar to how a name binding functions.
When the interpreter encounters this syntax here, it checks to see if this key exists in the dictionary. If it does it returns the value object. Because this is a stand-in for the value object for this key, we can perform operations with it. And these operations will apply to the value object.
In this example we’re using the assignment operator to assign the string Ada to the key name. Once this operation completes the dictionary now contains a key-value pair.
We can display a text based representation of this dictionary in the console by using the built-in print function. Which will show us the key-value pair of name and Ada.
Let’s add another key-value pair representing the cat’s age. We’ll set the value to 3. Printing this shows that we now have two key-value pairs.
Now, let’s imagine this cat had a birthday, and we need to increment the age by one. We can do that using the increment operator. Which results in the value for the key age being updated to 4.
Notice that regardless of the operator we use the same syntax to reference the value for the given key. What if we make a mistake, or maybe we just don’t need a key-value pair anymore?
By using the del keyword we can delete key-value pairs from a dictionary. Actually, the del keyword can be used to remove any name binding. Which includes a dictionary's key-value pairs. The syntax starts with the keyword del followed by the name to unbind, and therefore delete. Notice that the dictionary no longer includes the age key.
What if we don’t know if a key exists or not? Dictionary objects support the use of the in and not in operators.
Which can check for the existence of a key. For example: Does the key name exist in the cat dictionary? We can see it does so this returns True.
Using these operators allows us to check if a key exists or not. Besides the value-lookup syntax, there are other ways to interact with individual values using the dictionary’s methods.
There are several methods provided by dictionary objects. The get method is an alternative form of the square bracket syntax.
The method expects the key and returns the corresponding value. The update method is another alternative form of the square bracket syntax used to update a value.
These alternatives aren’t used as often as the square bracket syntax. However, there are some exceptions where the methods are more valuable. For example: if we use the square bracket syntax and the key doesn’t exist the runtime will raise an error.
Sometimes that might be what you need. However, other times you might be able to provide a default. The get method makes that easy by allowing us to specify an optional default value. If the key doesn’t exist, then it returns the default.
When dealing with dictionaries sometimes you want to see all of the keys or all of the values in the dictionary. And there are methods for both. The keys method returns a list containing all of the keys.
The values method returns a list containing all of the values. Know that there are other methods. Though, they’re not worth covering at this stage.
So, let’s talk about operators used to interact with the entire dictionary, rather than a single key-value pair. Imagine that we have two dictionaries. One contains some default configuration settings. The other contains the setting preferences for a user. Using the merge operator we can merge one dictionary on top of another.
This will result in the values from the default configuration being overwritten by the user_settings. This updates the left side dictionary with values from the right side.
Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:
The syntax for creating dictionaries:
uses curly brackets to define the dictionary
uses a colon to separate a key and value
uses a comma to separate pairs
The syntax for accessing an individual value based on its key
uses square brackets with the key inside the brackets
The syntax for deleting a key-value pair
uses the del keyword followed by the name to unbind.
The way to merge two dictionaries is to use the merge operator.
Alright, that's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.