In this week's Python snippet post, we're taking a look at dictionaries and some methods we can use for iterating over dictionaries in different ways.

First let's take a look at what happens when we iterate over a dictionary normally:

example_dict = {
    "name": "James",
    "age": 25,
    "nationality": "British"
}

for x in example_dict:
    print(x)

# name
# age
# nationality

By default, we just get the keys when we iterate over a dictionary. That might be what we want, but what if we want the values instead? Well, we can use the values method.

for value in example_dict.values():
	print(value)

# James
# 25
# British

We just call values on the dictionary we're iterating over, and we get the value for each key instead.

So can we get both at once? Absolutely!

Instead of using the values method, we can call the items method. This will give us a tuple for each key in the dictionary containing the key and the value in that order.

Generally, we're going to want to destructure this tuple into individual values like we see below:

for key, value in example_dict.items():
    print(key, value)

# name James
# age 25
# nationality British

This isn't necessary, however, and we could just as easily assign the tuple to a loop variable instead of splitting it up into its component parts.

Wrapping up

That's it for this short snippet post on iterating over dictionaries. The tools we talked about in this post are an absolutely vital part of Python development, so it's well worth getting familiar.

I hope you learnt something new, and if you're interested in upping your Python game, check out out Complete Python Course. Use coupon code BLOGGER to get it for just $9.99.