Adding and Iterating Keys and Values

Demonstrate dictionary manipulation and iteration techniques in Python.

Discover effective techniques for manipulating Python dictionaries, including dynamically updating values and efficiently renaming keys. Enhance your coding skills by mastering dictionary iteration and key-value management in Python.

Key Insights

  • Learn how to dynamically adjust dictionary values using shorthand operators such as "+=" for incremental changes and "*=" for percentage-based modifications, allowing efficient value updates.
  • Understand methods to rename dictionary keys indirectly by utilizing the "pop()" function to remove and simultaneously reassign values, enabling concise key renaming in a single operation.
  • Gain proficiency in iterating over Python dictionaries by directly looping through key-value pairs using the ".items()" method, simplifying the process of accessing dictionary contents during iteration.

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.

Now let's add another here, whoa, let's keep rolling.

Little challenge: add engine. Add a new key called engine, the value of which is a dictionary.

This is kind of like doing the mpg thing with city and highway, so the value will be a dictionary of three keys: hp, liter, and cylinder, and the respective values will be as shown.

Okay, and this get hp to make sure it worked, you can put that in—we'll just try that on our own. Just this: add the engine property.

So pause, give it a try. It's very much like the mpg one you see here, except there's three properties, not two.

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.

Remember you want to do the challenges. That's how you're going to get good. That's how the explanations will be more memorable and really click.

So please pause, try the challenge.

Okay, we're going to do the solution.

So to add engine, we would say car, engine. We would just declare the new property the way we did with doors, and the value would be a dictionary of three keys.

Each key would have its value as one of these numbers: 260, 5.0, and 8 for the horsepower, liters, and cylinders.

And there you go, we've got our new property.

Let's increase hp by one, whatever it is. We don't even know what it is—just up by one, so we're one, which should up it to 261.

Yep, the horsepower is now 261. And if you run this again, it'll be 262 and 263. += 1

And if we want to get back down to 260: 262, 261, 260.

So this += / -= syntax is good if you have a scenario where you need to maybe repeatedly target some property and have it go up by one—like you're keeping track of how many times something happens, a user logs in or something.

You can do math as well—other math moves besides adding by one.

Let's increase the miles by 10%. We'll say car['miles'] *= 1.1.

*= is shorthand for—but we could make it the longhand—car['miles'] = car['miles'] * 1.1.

That's... and there's your car miles.

Should probably round it off though, right?

Let's say round our miles. Now it's going to run it again. The miles keep going up by 10% every time we run this.

If you'd like the miles to get back down where they were, you could run it a few times, knocking it down by 10% every time—you'll get fairly close to where you were.

So targeting values for relative increase or—you know—increase by one from whatever it is, increase by 10% from whatever it is.

Now let's say we have a key that we want to change the name of.

You can't directly do that, but what you could do is you could remove a key you don't want but save the value of it and then just declare a new key and assign that.

Which we did—remember we popped off miles but saved it and then we reassigned miles.

Well at that point we could have changed the name of miles.

So let's declare a new property. We'll say car['odometer'] = car['miles'], which means we'll have a duplicate property, right?

We'll have two properties with the same value—right, we have odometer and miles. Right—duplicate values.

Well now that we've safely stashed the miles in the new property, all we have to do is delete the original.

We'll just say del car['miles'].

So in a roundabout way, we've effectively renamed—right, quote-unquote renamed—miles to odometer.

We didn't really directly rename miles to odometer, but we made a copy of miles called odometer and then just deleted the original miles. That's the move.

You could also do that in one fell swoop.

Let's say you wanted to rename it as—for example—rename for_sale with an underscore.

We could do this: we could say car['for_sale'] = car.pop('sale').

And remember pop returns the popped item, so we're going to pop off sale but immediately assign that value to a new key.

So that is a one-liner move for effectively changing the name of a property.

So for_sale now has an underscore, where it did not before.

So that's another way to change the name of a key in one line with pop or in two lines by making a copy and then deleting the original.

And we don't need that.

You can also make a list from keys, which is useful.

We're going to say car_keys = car.keys() or actually we're just going to—just take a list—I'm going to pass keys—pass the entire dictionary to the list method and see if that returns us a list of the keys.

And it does.

And we could say car_values = list(car.values()).

We have to kind of look up the values—the default is the keys when you do this move.

And then you get all—you know—a list of all the values, which might not be as interesting or useful.

It's really not. Typically you would have—you know—but it can be very useful to get all the keys into a list.

You could maybe use those for column headers in some data science scenario.

Let's turn off this value there—that is every single key as a list item. A list of keys.

Now you can also iterate keys.

You could either iterate the car_keys list that you made, or you could just directly iterate them—iterate the keys.

We can loop a dictionary key by key.

We could say for key in car—kind of like before. It's a for loop, except you're not looping a list, you're looping a dictionary.

We're not looping this car_keys list—we're looping the entire car dictionary, key-value pair by key-value pair.

And as we go every time, we're going to print the key.

Now you could also go, while you're doing it, and dynamically look up the value.

We could say f"...{key}: {car[key]}"—let's use our cool new way to concatenate, because you can't do regular concatenation with numbers anyway—and there's numbers there.

That's your key-value pairs—basically your properties printing out.

So notice here, the key is being fed in as a variable for lookup.

It's essentially a string, right? It is the double-quoted string.

If you pass it into the square brackets of the dictionary, it'll return or look up the value.

So you can loop and have individual access to the key—or the value.

You can also directly access the value.

We could say for key, val in car.items(), and then we don't have to look up the value—we'll just have it directly.

Let's just print—print the key.

You don't have to print car[key], now you don't have to look it up.

There—oops, key, val in car—oh, you have to say .items() to unpack both the key and the value.

There we go.

So sometimes you loop dictionaries—it does happen. You're doing most of your looping or iterating over lists, but it is possible to loop.

Because the dictionary has more than one item, it is an iterable—ergo a loopable thing.

We're going to finish with something fun here.

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