Python Dictionaries - Key-Value Pairs and Data Structures

Explain Python dictionaries, their structure, and how to manipulate values and nested data.

Explore Python dictionaries and discover how their key-value pairs offer powerful ways to organize data. Learn to create, access, modify, and manage dictionary data structures effectively.

Key Insights

  • Understand Python dictionaries as collections of key-value pairs stored inside curly braces, allowing various data types like strings, numbers, Booleans, lists, and even child dictionaries as values.
  • Learn dictionary manipulation techniques, such as accessing values via keys (e.g., car["make"]), updating properties, appending elements to nested lists, flipping Boolean values, and deleting properties using Python's del and pop methods.
  • Practice applying list methods within dictionaries by extending and alphabetizing list elements nested within dictionary properties.

Note: These materials offer prospective students a preview of how our classes are structured. Students enrolled in this course will receive access to the full set of materials, including video lectures, project-based assignments, and instructor feedback.

This is a lesson preview only. For the full lesson, purchase the course here.

Hi, welcome back to this course on Python programming and data science. My name is Brian McLean. Thanks for coming back for lesson five, in which we're going to get into yet another brand-new topic, this one called dictionaries.

So, as we have seen, every one of our lessons has been devoted to a fresh, big topic. Lesson one, variables and data types. Lesson two, conditional logic with if-else.

Lesson three, modules. Lesson four, which we just completed, covered loops and string methods. I'm in file five.

We're going to import pprint. We're going to be printing these dictionaries that we'll talk about, learn all about, and they're kind of big objects. So they'll display better and be more readable if we pretty-print them.

So a dictionary is a collection. It's an iterable structure because it has multiple values like a list, so you could loop it. A dictionary is actually sort of like a cousin of a list.

Python for Data Science Bootcamp: Live & Hands-on, In NYC or Online, Learn From Experts, Free Retake, Small Class Sizes,  1-on-1 Bonus Training. Named a Top Bootcamp by Forbes, Fortune, & Time Out. Noble Desktop. Learn More.

It's in the same category of what is known as a collection. So a collection is an iterable data structure, something that can hold more than one value. They include lists, sets, which we've looked at that don't have index values or positions, no duplicates, and items stored in curly braces as opposed to lists with which we're well familiar.

They've got multiple items stored by index or position number inside square brackets. Which brings us to dictionaries. A dictionary does not store items by index, so there is no position number.

Instead, it stores them by what is called a key. So it's basically a name for the item—key-value pairs.

And it'll make more sense when we start typing this and looking at the structure. But dictionaries are the third of four kinds of collections. We'll leave tuples until we get into data science.

We got into lists and sets and now dictionaries. We're going to declare a dictionary and give it many properties. Dictionary values—all the key-value pairs of a dictionary, or the properties as they're called—go inside curly braces.

So let's declare a dictionary and give it many properties as key-value pairs, as they're called. The keys go in quotes and the values can be any data type including a child dictionary. So let's say we're going to make a dictionary called car.

If anyone has a background in other programming languages, lists are called arrays in JavaScript, and dictionaries are known as objects in JavaScript. So car equals curly braces. And inside the curly braces, we're going to put a few properties.

Let's use this text here. The first property we want is going to be make, to be more specific for cars. The make of the car is Ford, and then the model of the car will be Mustang GT.

And the options of the car will be a list. So these—make, model, and options—are called keys. What follows on the right side are the values.

The keys always go in double quotes, and the values only go in double quotes if they're strings. Otherwise, they're whatever the data type is. And options is taking a value whose data type is a list.

Let's drop in a couple of numeric values. We'll have a key called year. The value will be a number.

And we'll have miles. How many miles are on the car? That's another number. Again, so we have five properties as key-value pairs.

Two of the values are strings, two numbers, and a list so far. You can have any data type, Boolean. Let's say for sale.

Make that true or make that false. And on road. Now, I'm deliberately making a space here because keys are variables.

They're names with values. So they're kind of like just regular variables, but they're different. Like we don't put variable names in quotes, right? First name doesn't go in quotes.

Only the value would go in quotes, right? If we had first name, you would never print first name in quotes, right? You would just literally get first name. Let's run this too. So here's the idea.

If you wanted to print the first name, you would print it without quotes, right? Variable names don't go in quotes. Keys are like variables, sort of, but with differences. Sort of.

They have values like variables, like regular variables. Keys have values of various data types, but unlike regular variables, keys go in quotes and can have spaces unlike regular vars. So here's a regular variable, and you cannot have a space, right? You cannot declare the variable like that, but when you're dealing with a string, you can have a space, but that's not a variable anymore.

That's just a string, right? These are just strings. If you want the value of a variable, don't put it in quotes. These are regular variables.

Now, coming back to the idea of a key-value pair, the keys go in quotes, so they are variables in the sense that they do have values associated with them, assigned to them, but because they go in quotes, they can have spaces, which you can't have in a regular variable. So for sale and on road could be written like regular variables with an underscore connector, or you could just have a space. Keys can have spaces, so they're not exactly the same as regular variables.

Key values can be of any data type, including lists or child dictionaries. In other words, the value of a dictionary property can be another dictionary. So let's say we have MPG city, let's say 18, and MPG highway, 24.

Now, that's okay. You can do that. Why is it not, like my—oh, I need a comma.

So you can have these MPG city and MPG highway as separate properties, but it's not great practice to do that. Because they're related properties, better would be to bundle them under the name of just MPG, and then we would say the value will be a child dictionary with two properties, city and highway. Because they're related properties, we'd like to keep them.

We've got five different data types of our values: string, number, Boolean, list, and dictionary. So a dictionary with a property, the value of which is a child dictionary. Let's run all that.

Now, let's read or get some of the values from our dictionary. So let's—we want to get the make; let's say car, square bracket, make. So the way to look up a property of a Python dictionary is to put the name of the dictionary.

So it goes dictionary[key]. It's not dictionary.key like you might in JavaScript. Square brackets with quotes.

So you go look up—it's basically you're looking up the value of make with the square-bracket syntax. It returns you Ford—whatever the value of the make is. And model—you want to know what the model is? It's dictionary[key] model.

And we'll just keep doing that. We'll say year or sale. Year would be 2003; for sale is False, and so forth.

Now what if we print—let's try to print, let's see what we have so far. Ah, we have an error. We got Ford Mustang GT 2003 False, but then we got an error on options.

We tried to look up the option at index two, which would be sports package. That's because options doesn't exist as a separate variable. You have to look it up on car, right? Options exists as a property of car.

And then you—let's just get the whole options. There you go. And then we could say option zero.

We'll do that like so. That would be all options as a list—first item in the options list. If you want the sports package, that would be the next item.

And you can't use dot syntax to get it like that. That doesn't work. So let's say, let's get the 24.

Get the 24. So what is the 24? The 24 is the value of the highway property of the child dictionary, which is the value of the MPG property. To get that, we certainly cannot just log highway.

Well, even if we say car highway, that won't work. Error. There's no such thing.

We have to say car MPG highway. We have to drill because it's a child—because highway is a property of a dictionary, which is the value of another property. So first you have to, starting from car, get to the MPG.

You have to look up the value of the MPG key, which is a dictionary. Then you have to look up the value of the HWY property—highway property—of that dictionary. So it goes car square bracket MPG square bracket highway.

And if you just say car zero—no, it would have to be car. Again, option zero. Oh, well, actually, let's say you think, okay, I just want to get the first item.

You know, it's like fruits. Apple is the first item. So make is the first item, right? Doesn't work that way.

Dictionaries don't exist by index. There's just no key. It's thinking there's a key called zero—KeyError: 0.

So dictionary properties do not exist by index. You can't look them up the way you would look up fruits and, you know, look up apple at fruit zero. Doesn't exist.

No indexing in dictionaries. We're going to set or update. Okay.

We're going to set a property—that would be change or update. So it's just like getting the property, except you change the value. So let's say car year equals 2002.

And then we'll pprint car. And now the year is 2002 because we set it, right? We targeted it by property and gave it a new value. Let's do the miles as well.

So it was 56,789. Now let's say it's 57,890. We've got new updated values for year and miles.

We could also add a new option. Let's add sunroof. Well, that would be putting a new value into a list.

So you would have to append car options—that is, the name of the list—dot append, and we want to append the sunroof.

Run. And there's your sunroof. And again, we're using pprint.

Let's not run the cell again. It'll append another sunroof. Now flipping a Boolean.

Let's say you want to list the car for sale. We could say car for sale equals True. Or let's say we didn't know what it was.

We just want to flip it. We could say not for sale and then run. And the car should now be for sale.

And if we run it again, it's not for sale. And if we run it again, it's for sale because we're flipping it every time. We're setting it to be not what it was.

And that's a Boolean. So remember the not operator for flipping Booleans. To delete a property, use the del keyword.

So let's say we want to get rid of the on road property altogether. Just take it out. Just decide we don't need that.

We're just going to say del. del car['on road']. And then we want to run this twice because this is a destructive move.

If you run it ever again, it'll give you an error because there won't be an on road property to delete anymore. So there's on road. And here's no more on road property.

Delete with del. You can also save a property—you can delete yet save one.

When you delete a property—so what we could do is, let's say we wanted to delete a property but we wanted to save the data first—we'll say car miles equals car.pop('miles').

We're going to use pop—pop by key—to remove it.

And let's see what we get. There. It worked.

We popped it. Why would we want to do that? Well, maybe we didn't like the name. We'll come back.

Let's put it back. We'll say car miles equals car miles. We're going to put it back there.

So miles are back. Popped. Saves.

Return. If we catch it, we have it. And then you can just reassign it.

  1. We did that move. Now making a new property.

To add a property, it's the same as just reading an existing one. We'll say car doors. Now that property doesn't exist, but it will now get made just by referring to it.

Now you have a property called doors. Basically declare it the same way you'd read the property, and if it doesn't exist and you set the value, it'll make the property.

If it already exists, it'll set the value to what you say. If you don't want to change the value, just read the value. Just car doors, right? It'll say this is just reading it without changing it.

All right. Challenge. Let's add three new options.

Subwoofer, CD player, and flame decals. Do we already have all that stuff? Nope. Then alphabetize the options.

Pause. Try it. This is a review of list methods, but it's just seeing if you can access a list from within this car dictionary.

So pause, give it a try, and we'll do the solution. OK. We're going to add three new options.

We'll say car options—that's the list—extend, because we want to do three of them.

And we will do that. We'll just copy-paste like that. And you've got your new values.

All right. Let's not add anything more to this cell, because we don't want to add the three items yet again.

Now we'll say car options.sort, and then output the car. Now the options are alphabetized.

Brian McClain

Brian is an experienced instructor, curriculum developer, and professional web developer, who in recent years has served as Director for a coding bootcamp in New York. Brian joined Noble Desktop in 2022 and is a lead instructor for HTML & CSS, JavaScript, and Python for Data Science. He also developed Noble's cutting-edge Python for AI course. Prior to that, he taught Python Data Science and Machine Learning as an Adjunct Professor of Computer Science at Westchester County College.

More articles by Brian McClain

How to Learn Python

Master Python with hands-on training. Python is a popular object-oriented programming language used for data science, machine learning, and web development. 

Yelp Facebook LinkedIn YouTube Twitter Instagram