Skip to content

Python Dictionaries: A Complete Overview

Python Dictionaries A Complete Overview Cover Image

Python dictionaries are an incredibly useful data type, which allow you to store data in key:value pairs. In this tutorial, you’ll learn all you need to know to get up and running with Python dictionaries, including:

  • The basics of creating dictionaries to store and access data
  • What the best use cases for dictionaries are
  • Adding and removing data from dictionaries
  • How to apply functions and methods to dictionaries

Let’s get started!

What are Python Dictionaries?

Python dictionaries are container data types, like Python lists. Dictionaries use a key-value pair mapping, allowing you to retrieve a value by looking up its corresponding key. They are very similar to what, in other programming languages, is called an associative array. This is because it’s an array of data that is associated to something else – in this case, a key.

Unlike Python lists, which are sequence data types, Python dictionaries work a little differently. Because lists are sequenced, we can access items based on their position. For example, to access a particular item in a Python list, we can simply reference its index:

# Getting the second item in a Python list
names = ['Nik', 'Kate', 'Evan', 'Kyra']
second_name = names[1]
print(second_name)

# Returns: Kate

Because Python dictionaries aren’t a sequence data type, we can’t simply access, say, the first item. In order to access a particular value in a Python dictionary, we use a key in the dictionary to access the value.

In a Python dictionary, you can have multiple keys. These keys must be:

  • Unique – a given key can only exist a single time
  • Immutable – meaning that keys must be of data types that cannot be altered, such as strings

Think of Python dictionaries as, well, dictionaries. You can look up the value of a word (i.e., a key) and it’ll give you the corresponding definition (i.e., its value).

Creating a Python Dictionary

Let’s take a look at how we can create a Python dictionary. To start off, we’ll create an empty dictionary. We have two main ways of accomplishing this:

# Creating a Python Dictionary
dictionary1 = {}
dictionary2 = dict()

We can check the type of these dictionaries by using the built-in type() function:

# Checking Dictionary Types in Python
print(type(dictionary1))
print(type(dictionary2))

# Returns:
# <class 'dict'>
# <class 'dict'>

Similarly, we can load a populated dictionary by loading it directly. Let’s take a look at how this looks by loading a dictionary with a person’s attributes:

# Creating a Sample Python Dictionary
nik = {
    'age': 33,
    'location': 'Toronto',
    'company': 'datagy.io',
    'hobbies': ['Python', 'Long walks on the beach', 'Travel']
}

We can see we were able to embed quite a few different items as values here. To name a few, we have an integer (representing an age), strings (representing, say, a location), and even lists!

You don’t actually need to write this out across separate lines, but it’s much easier to read. We could have accomplished the same thing by simply writing:

# Creating a Sample Python Dictionary
nik = {'age': 33, 'location': 'Toronto','company': 'datagy.io','hobbies': ['Python', 'Long walks on the beach', 'Travel']}

Now that you have a strong understanding of how to create Python dictionaries, let’s take a look at how to use them.

How Are Dictionaries Related to Data Science?

At this point, you may be wondering how dictionaries are related to data science? When we access data from the web it often comes in a format know as JSON (JavaScript Object Notation). This format very closely resembles the format of Python dictionaries.

Knowing how to work with Python dictionaries allows us to easily download data from the web and manipulate it. The format is incredibly common and will offer up significantly higher flexibility in terms of accessing and working with data from different sources.

Working with Python Dictionaries

Being able to create Python dictionaries is one thing, but you also need to know how to work with them. In this section, you’ll learn different ways of accessing dictionary items, modify items, and how to add and remove items. There are different ways in which to accomplish all of this but you’ll learn the safest and most common ways of accomplish this.

Accessing Items in Python Dictionaries

There are two main ways in which we can access items inside of a dictionary. We can use square brackets, [], similar to accessing a list item using its index. We can also use the .get() method.

Let’s take a look at how we can use the square brackets to access an item.

# Accessing Dictionary Items with Square Brackets
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
print(info['name'])

# Returns: Nik

That was easy! One of the quirks of using the square brackets method of accessing items is that it doesn’t work well with items that don’t exist.

Try running the code below to access an item that doesn’t exist, such as 'hobbies' to see what happens:

We can see that when we try to access an item that doesn’t exist that a KeyError is thrown. This indicates to us that a key doesn’t exist. What’s worse is that this actually crashes our program (unless we explicitly handle that error).

One way that we can work around this is by using the .get() method. The .get() method will simply return the None value when a key doesn’t exist.

The method works by applying it to a dictionary and passing in the key for which we want to return the value. Let’s see how we can use this to return the value for 'name':

# Accessing Dictionary Items with Square Brackets
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
print(info.get('name'))

# Returns: Nik

One of the perks of using the .get() method is that we can even pass in a default value that we want returned when a key doesn’t exist. For example, say we had intended to have a key named 'hobbies' which would contain a list of different hobbies. Instead of returning None, we could ask Python to return an empty list.

See if you can write the code below to make this happen. The solution is accessible by selecting the toggle:

A Potential Solution

# Getting Dictionary Items that don't exist

info = { 'name': 'Nik', 'age': 33, 'location': 'Toronto' }

print(info.get('hobbies', []))

Adding Items to Python Dictionaries

Adding items to a Python dictionary is incredibly easy! We can simply directly assign a key:value pair onto the dictionary.

Let’s see what this looks like. We’ll want to add an item of hobbies into our dictionary.

# Adding Items to a Python Dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
info['hobbies'] = ['Coding', 'Long Walks on the Beach']

print(info)
# Returns: {'name': 'Nik', 'age': 33, 'location': 'Toronto', 'hobbies': ['Coding', 'Long Walks on the Beach']}

Python also provides a number of ways to merge two dictionaries together. This can be incredibly helpful if data has been collected separately and you don’t want to manually update items in one dictionary with the items of another.

For this, we can use the .update() method. Similarly, we can use the | operator in Python 3.8+. Both these methods work in the same way, in that the dictionary on the right will merge into the dictionary on the left. Any new key-value pairs will be added, while any existing keys in the left dictionary will be updated with values on the right.

# Merging two dictionaries in Python
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
more_info = {'company': 'datagy.io', 'location': 'Toronto, ON'}
# info.update(more_info)          # Or use in Python 3.8+: info |= more_info

print(info)
# Returns: {'name': 'Nik', 'age': 33, 'location': 'Toronto, ON', 'company': 'datagy.io'}

We can see that new items from the more_info dictionary were added, while existing items were updated. Keep this in mind as you update information!

Modifying Existing Python Dictionary Items

Modifying existing items works the same as adding new ones! We can simply directly assign a value to an existing key and update its value. The added benefit of this is that if an item doesn’t exist, that a new one gets added.

Let’s take a look at adding modifying our key 'location' key in our dictionary:

# Modifying items in a Python dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
info['location'] = 'Toronto, ON'
print(info)

# Returns: {'name': 'Nik', 'age': 33, 'location': 'Toronto, ON'}

There’s not much more to this! Let’s take a look at how to remove items from a Python dictionary.

Removing Items from Python Dictionaries

Similar to lists, Python provides a number of different ways to remove items from dictionaries. The first approach we’ll take a look at is the del keyword. The keyword accepts a dictionary item and removes the item from the dictionary.

Let’s see how we can use the keyword to delete an item:

# Deleting an item from a dictionary with del
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
del info['age']
print(info)

# Returns: {'name': 'Nik', 'location': 'Toronto'}

We can also use the Python .pop() method to remove an item from a dictionary. The benefit of this approach is that it returns the value before removing the key-value pair. Let’s see what this looks like:

# Using .pop() to delete an item from a dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
age = info.pop('age')

print(age)
print(info)

# Returns: 
# 33
# {'name': 'Nik', 'location': 'Toronto'}

With both of these methods, we need to be careful to not remove keys that don’t exist. Both of these methods will return a KeyError if we try to delete a key that doesn’t exist. Let’s confirm this:

# Attempting to delete a key that doesn't exist
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
age = info.pop('hobbies')

# Raises: KeyError: 'hobbies'

The .pop() method does allow us to provide a default value so that your program doesn’t crash when a key doesn’t exist. This allows us to run the program more safely.

Let’s see how this works:

# Running .pop() safely with a default value
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
age = info.pop('hobbies', [])
print(age)

# Returns: []

While, of course, this doesn’t delete the key, it allows us to more safely write programs that require accessing and removing a key from a dictionary.

Python Dictionary Methods

Python dictionaries provide many different methods – you’ve even already learned a few of them! In this section, you’ll learn a few more that allow you to access the keys and values of dictionaries.

Accessing Dictionary Items with .items()

We can use the .items() method to easily retrieve all of the items in a dictionary. Applying this method returns a list-like object that contains tuples containing the key and the value of each item in the dictionary.

This can be incredibly helpful if you want to loop over the keys and the values. Let’s see what this looks like:

# Getting items from a dictionary with .items()
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
print(info.items())

# Returns: dict_items([('name', 'Nik'), ('age', 33), ('location', 'Toronto')])

We can iterate over this dict_items object in order to access both the keys and the values. You’ll learn this in the following section on iterating through dictionaries.

Accessing Dictionary Keys with .keys()

We can easily access all the keys in a dictionary by using the .keys() method. This returns a list-like object that contains allow of the keys.

Let’s take our earlier dictionary and apply the .keys() method:

# Getting all dictionary keys with .keys()
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
print(info.keys())

# Returns: dict_keys(['name', 'age', 'location'])

Accessing Dictionary Values with .values()

Similar to the .keys() method, we’re able to access all the values in a Python dictionary using the .items() method. This also returns a list-like object that contains the values of all keys in a dictionary.

Let’s apply the .items() method to our dictionary:

# Getting all dictionary values with .values()
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
print(info.values())

# Returns: dict_values(['Nik', 33, 'Toronto'])

Checking Membership in Python Dictionaries

We can easily check for membership in a Python dictionary by using the in keyword. Let’s see how we can see if a key exists in a Python dictionary by using the .keys() method:

# Check if a key exists in a dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
if 'name' in info.keys():
    print('Exists!')
else:
    print("Doesn't exist!")

# Returns: Exists!

We can actually simplify this process by not using the .keys() method. By default, Python will check for membership in the keys of a dictionary. Because of this, we can even drop the method from our membership check:

# Check if a key exists in a dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
if 'name' in info:
    print('Exists!')
else:
    print("Doesn't exist!")

# Returns: Exists!

In the next section you’ll learn how to iterate through Python dictionaries.

Iterating through Python Dictionaries

Now that you have a strong understanding of how to access items, keys and values in Python dictionaries. Let’s take a look at how we can iterate over Python dictionaries.

Because the .items(), .keys(), and .values() methods all return list-like objects, we can iterate over them directly. Let’s take a look at how to iterate over the keys first:

# Iterating over all keys in a dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
for key in info.keys():
    print(key)

# Returns: 
# name
# age
# location

This approach works the same for .items().

But what if you wanted to iterate over the keys and values in one go. For this, you can use what’s known as unpacking. We can iterate over the .items() method return and unpack the key and value from the returned tuple.

Let’s see what this looks like:

# Iterating over both keys and values in a dictionary
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto'}
for key, value in info.items():
    print('Key = ', key, ', Value = ', value)

# Returns: 
# Key =  name , Value =  Nik
# Key =  age , Value =  33
# Key =  location , Value =  Toronto

In the final section below, you’ll learn whether or not Python dictionaries are ordered or not.

Are Python Dictionaries Ordered?

Answering whether Python dictionaries are ordered or not is not a simple yes or no. Prior to version 3.6 of Python, dictionaries were unordered. Beginning in Python 3.6 (and more formally so in Python 3.7), Python dictionaries are ordered.

What does this mean? Python dictionaries are now ordered based on the insertion order. The benefit of this is faster retrieval.

Exercise

Below you’ll find a couple of exercises to help you check your understanding of Python dictionaries. Use the code workspace provided to test your solutions. You can toggle the sections to check the solutions.

Create a dictionary like the one below and complete the following exercises:

# Load the dictionary into the code editor below
info = {'name': 'Nik', 'age': 33, 'location': 'Toronto', 'company': 'datagy.io'}

Print out all the values of the dictionary using a for loop.

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

Add a new key that contains a list of values.

info['Favourite Snacks'] = ['Popcorn', 'Cookies']

Update the location key to ‘Vancouver’.

info['location'] = 'Vancouver'

Conclusion and Recap

Phew! You made it to the end of the tutorial! There was a lot to learn about Python dictionaries and you’ve learned a ton about them!

Below, you’ll find a quick recap of everything you learned about Python dictionaries:

  • Dictionaries are an associative array of values containing key-value pairs
  • Keys must be immutable and unique
  • Values can be any type of value and can be duplicated
  • You can create dictionaries with the use of the dict() function or curly braces {}
  • Dictionaries are similar to the JSON format which is often used to store data on the internet
  • We can add items by simply assigning a value to a key
  • We can delete items using del or .pop()
  • The .pop() method allows us to pass in a default value which allows our program to run safely if a key doesn’t exist
  • We can access items using the .items(), .keys(), and .values() methods

Additional Resources

Check out the tutorials below for some additional resources:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

6 thoughts on “Python Dictionaries: A Complete Overview”

  1. Man this website turned out a charm for me.
    I can’t express how much I learn in these 6 days.
    I hope you (nik) will upload such interesting and amazing python and data science articles and tutorials.
    Thanks Nik

  2. Nik, sorry to bother you, but I find that using the union operator (|) without re-assign it to another dictionary actually happens in place too as same as the update() method. Did I misinterpret your meaning?

Leave a Reply

Your email address will not be published. Required fields are marked *