Python Dictionaries: Everything You Need to Know

This article was first published on python – Better Data Science , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.

Dictionaries are awesome. They allow you to store and structure nested data in a clean and easy-to-access way. Today we’ll explore everything there is to Python dictionaries and see how you can use them to structure your applications.

Don’t feel like reading? Check out my video on the topic:

Dictionaries are somewhat similar to lists. Both are dynamic, meaning they can store any data types, and both are mutable, meaning you can change them throughout the application.

What makes dictionaries different is the storage type. They store key-value pairs instead of a raw number or text. Further, you can access dictionary elements through a key instead of an index position, as is the case with lists.

Accessing a key returns a value – that’s the general behavior you should remember.

Here’s what you’ll learn today:

There are many topics to cover. Please follow them in specified order if this concept is new to you. If not, feel free to skip to any section.

Declaring a dictionary

There are multiple ways to create a dictionary. None of them is better than the other, so feel free to pick one that best suits your coding style.

The first way is the one you’ll find in most of the examples online, so we’ll stick to it throughout the article. In this style, you are putting keys and values separated by a colon inside curly brackets. Here’s an example:

d = {
    'Country': 'USA',
    'Capital': 'Washington, D.C.'
}

The second style uses the dict keyword to declare a dictionary, and than places the elements as tuples (key, value) inside a list:

d = dict([
    ('Country', 'USA'),
    ('Capital', 'Washington, D.C.')
])

It’s not the most convenient method if you ask me. There are way too many parentheses, which ruin the code’s cleanness if the dictionary has nested elements.

The third approach also uses the dict keyword, but the style looks more like assigning values to function parameters:

d = dict(
    Country='USA',
    Capital='Washington, D.C.'
)

Note how quotes aren’t placed around the keys with this approach.

Once again – the style you choose is irrelevant. 

Basic dictionary operations

In this section, you’ll learn how to access dictionary values, change them, and delete them.

To access dictionary values, you can use the dict[key] syntax. Let’s see how to print values of both Country and City from the dictionary d:

print(d['Country'], d['Capital'])

Executing this code prints “USA Washington, D.C.” to the console.

Next, let’s see how to change the values. You can still use the dict[key] syntax, but you’ll have to assign a value this time. Here’s how:

d['Country'] = 'France'
d['Capital'] = 'Paris'

If you were to reuse the first code snippet from this section, “France Paris” would be printed to the console.

Finally, let’s see how to delete a key. Python has a del keyword that does the job. Here’s how to use it:

del d['Capital']

If you were to print the entire dictionary, “{‘Country’: ‘France’}” would show. The Capital key was deleted successfully.

Nested dictionaries

Nested dictionaries have either dictionaries or lists as values for some keys. If you make a request to almost any REST API, chances are the JSON response will contain nested elements. To oversimply, consider JSON and nested dictionaries as synonyms. Therefore, it’s essential to know how to work with them.

Let’s declare a nested dictionary:

weather = {
    'Country': 'USA',
    'City': 'Washington, D.C.',
    'Temperature': {
        'Unit': 'F',
        'Value': 54.3
    }
}

The Temperature key has a dictionary for a value, which further has two key-value pairs inside. The nesting can get a lot more complicated, but the principles remain identical.

Let’s now see how to access the City key. This should be a no-brainer, as the mentioned key isn’t nested:

weather['City']

The value of “Washington, D.C.” is printed to the console.

Let’s spice things up a bit. To practice accessing nested values, you’ll have to access the value located at Temperature > Value key. Here’s how:

weather['Temperature']['Value']

The value of “54.3” is printed to the console.

And that’s all you should know about nesting. Once again, nesting can get way more complicated, but the logic behind accessing elements always stays the same.

Check if a key exists in a dictionary

Checking if a key exists is common when working on programming or data science tasks. In this section, you’ll learn how to check if a key exists, if a key doesn’t exist, and how to check if multiple keys exist.

Let’s start with checking if a single key exists. You can use Python’s in keyword to perform the check:

'Country' in weather

The code above outputs True to the console. Let’s perform the same check for a key that doesn’t exist:

'Humidity' in weather

As you would expect, False is printed to the console.

Let’s now see how to check if a key doesn’t exist in a dictionary. You can use Python’s not keyword combined with in. Here’s an example:

'Humidity' not in weather

The above code prints False to the console.

Finally, let’s see how to check for multiple keys. You can use Python’s and and or keywords, depending on if you need all keys to be present or only one:

'City' in weather and 'Humidity' in weather
'City' in weather or 'Humidity' in weather

The first line outputs False, and the second one True. You can put as many conditions as you need; there’s no need to stop at two.

Dictionary methods

This section is the most useful one for practical work. You’ll learn which methods you can call on dictionaries and how they behave.

get()

This method is used to grab a value for a particular key. Here’s how to grab the value for City of the weather dictionary:

weather.get('City')

As you would expect, “Washington, D.C.” is printed to the console.

keys()

This method returns all of the keys present in a given dictionary:

weather.keys()

The output is: dict_keys(['Country', 'City', 'Temperature']).

values()

The values() method is very similar to the previous one, but returns dictionary values instead:

weather.values()

The output is: dict_values(['USA', 'Washington, D.C.', {'Unit': 'F', 'Value': 54.3}])

items()

This method returns a list of key-value pairs found in a dictionary:

weather.items()

The output is: dict_items([('Country', 'USA'), ('City', 'Washington, D.C.'), ('Temperature', {'Unit': 'F', 'Value': 54.3})])

pop()

The pop() method removes a key-value pair from the dictionary and returns the value. The removed value can be stored in a variable:

pop_item = weather.pop('City')
weather

After removing the City key, the dictionary looks like this: {'Country': 'USA', 'Temperature': {'Unit': 'F', 'Value': 54.3}}.

popitem()

This method is similar to the previous one, but it always removes the last key-value pair. The removed value can be stored in a variable:

last_item = weather.popitem()
weather

The output is: {'Country': 'USA'}. As you can see, the Temperature key and its value were successfully removed.

clear()

This method is used to delete everything from a dictionary. Here’s an example:

weather.clear()
weather

The output is an empty dictionary – {}.

update()

This is the last method we’ll cover today. Put simply, it is used to merge two dictionaries. If the same keys appear in both dictionaries, the value of the latter is preserved:

d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = {'d': 10, 'e': 11, 'f': 12}
d1.update(d2)
d1

Here’s the output: {'a': 1, 'b': 2, 'c': 3, 'd': 10, 'e': 11, 'f': 12}.

Dictionary unpacking

The unpacking operator provides a more Pythonic way of performing dictionary updates. Unpacking is widely used in data science, for example to train a machine learning model with a set of hyperparameters stored as key-value pairs in a dictionary.

To perform the unpacking, you can use the ** operator before a dictionary.

Let’s cover unpacking with an example. Suppose you have the following two dictionaries:

d1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
d2 = {'e': 5, 'f': 6, 'g': 7}

You want to store all key-value pairs in a single dictionary. Here’s how to do this with unpacking:

unpacked = {**d1, **d2}

Neat, right? The unpacked dictionary contains the following elements: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7}

Dictionary comprehensions

Don’t let the fancy naming fool you – this is a simple concept. You are probably already familiar with comprehensions, but with lists. As it turns out, you can do the same with dictionaries.

If you aren’t familiar, don’t worry, there isn’t much to it. Dictionary comprehensions are methods for transforming one dictionary into another. Comprehensions are a neat way to avoid writing loops.

Let’s get practical. Suppose you have the following dictionary of scores on a test:

scores = {
    'Bob': 56,
    'Mark': 48,
    'Sarah': 77,
    'Joel': 49,
    'Jane': 64
}

For whatever reason, you’re feeling generous today and are giving ten extra points to every student. Instead of writing a loop and reassigning values in that way, you can use comprehensions:

added_10 = {key: value + 10 for (key, value) in scores.items()}

The added_10 dictionary contains the following: {'Bob': 66, 'Mark': 58, 'Sarah': 87, 'Joel': 59, 'Jane': 74}.

Awesome! For the next example, you want to find out which students passed the test. 50 points is the pass threshold:

has_passed = {key: True if value > 50 else False for (key, value) in scores.items()}

The has_passeddictionary looks like this: {'Bob': True, 'Mark': False, 'Sarah': True, 'Joel': False, 'Jane': True}.

And that’s just for today. Let’s wrap things up in the next section.

Conclusion

Today you’ve learned pretty much everything there is about dictionaries. You can do other things, of course, but I didn’t find them useful in my daily job.

This article alone should serve you well for any use case – from programming to data science and machine learning.

What’s your most common operation performed with dictionaries? 

Join my private email list for more helpful insights.

The post Python Dictionaries: Everything You Need to Know appeared first on Better Data Science.

To leave a comment for the author, please follow the link and comment on their blog: python – Better Data Science .

Want to share your content on python-bloggers? click here.