Back to articles list Articles
10 minutes read

13 Python Dictionary Examples for Beginners

Want to master dictionaries, one of Python’s core data types? This article contains 13 Python dictionary examples with explanations and code that you can run and learn with!

Dictionaries are one of Python’s most fundamental data types; they are widely used to represent real-world data and structures. To truly master Python programming, you need to know how dictionaries work and what you can do with them. And what better way to achieve this other than checking out some Python dictionary examples for beginners?

In this Python dictionaries tutorial, we will go over examples on how to use and work with Python dictionaries. We will start with a quick recap on what dictionaries are and then move on to our examples.

If you want a deeper dive on dictionaries and other data structures, consider checking out our Python Basics; Part 2 course. It contains over 70 exercises to help you master the language. Otherwise, let’s move on with the article!

What Are Python Dictionaries?

Essentially, Python dictionaries allow you to create association between two values. These associations are called key-value pairs, where each key is associated with its corresponding value.

The code below represents a dictionary where each fruit is associated with its corresponding color:

fruits = {"banana": "yellow", "strawberry": "red", "grapes": "purple"}

If we think about our daily life, there are many moments where these associations come up naturally. For example:

  • Each product in a supermarket is associated with its price.
  • Each student in a school is associated with their grade.
  • Each customer ID in a company is associated with a customer name.

 

Python dictionaries allow us to represent these real-world associations in our code. As you may imagine, this is extremely helpful for answering questions like “what’s the price on product X?”, or “what is the grade for student Y?”.

The nature of the key-value pair is arbitrary: we can associate strings to integers, integers to other integers, strings to lists, etc. The only limitation is that the key in a key-value pair cannot be a mutable data type. This means that you cannot use a list as a dictionary key, for example.

How to Create a Dictionary in Python

Creating a Dictionary Literal in Python

We can create dictionaries in Python using curly braces { } . Inside the braces, we declare each key-value pair using colons  :  and we separate key-value pairs from each other using commas  , .

Here’s how a simple dictionary looks:

products = {'Jeans': 49.99, 'T-Shirt': 14.99, 'Suit': 89.99}

Any whitespace in the dictionary is ignored. You can leverage this fact and use line breaks so that each key-value pair sits in a single line. This improves readability and is especially helpful when the dictionary has many entries:

products = {
    'Jeans': 49.99,
    'T-Shirt': 14.99,
    'Suit': 89.99,
}

You can also declare an empty dictionary using curly braces without any values inside them:

empty_dict = {}

Creating a Dictionary in Python with the dict() Function

Another way to create a Python dictionary is using the dict() function. It accepts arbitrary keyword arguments and transforms them into key-value pairs:

products = dict(Jeans=49.99, TShirt=14.99, Suit=89.99)

The only limitation in this method is that the keyword arguments are always interpreted as strings. You should stick to the first method if your dictionary keys are integers (for example).

You can also use the dict() function to create an empty Python dictionary:

empty_dict = dict()

You can also read our article on 5 different ways of creating dictionaries in Python if you’re interested in finding out more. Otherwise, let’s keep going!

Common Dictionary Operations in Python

In this section, we will learn about some widely used operations that you can perform with Python dictionaries. We will use the following dictionary of countries and their capital cities:

countries = {'France': 'Paris', 'Japan': 'Tokyo', 'Chile': 'Santiago'}

Accessing and Modifying Key-Value Pairs

We can access values in a dictionary by providing its corresponding key in brackets:

print(countries['France'])
# output: Paris

print(countries['Japan'])
# output: Tokyo

What if the key does not exist in the dictionary? In this case, Python raises a KeyError:

print(countries['Canada'])
KeyError: 'Canada'

We can both create and update a key-value pair using the assignment ( = ) operator and providing a value for the given key:

# Creating a new key-value pair
countries['Canada'] = "Ottawa"

# Updating an existing key-value pair
countries['France'] = "????"

print(countries)
# output: {'France': '????', 'Japan': 'Tokyo', 'Chile': 'Santiago', 'Canada': 'Ottawa'}

Notice how the old value "Paris" for the key "France" is gone? This is another important detail of a Python dictionary: its keys are unique. If you update the value associated with a given key, its previous value is lost. Python dictionaries cannot have duplicate keys!

Getting All Keys and Values

We can use the dict.keys() and dict.values() methods to view the dictionary’s keys and values, respectively:

print(countries.keys())
# output: dict_keys(['France', 'Japan', 'Chile'])

print(countries.values())
# output: dict_values(['Paris', 'Tokyo', 'Santiago'])

These so-called views are not exactly lists: they are linked to the original dictionary. If the dictionary gets updated, the view is automatically updated as well:

keys_view = countries.keys()
print(keys_view)
# output: dict_keys(['France', 'Japan', 'Chile'])

countries['Canada'] = "Ottawa"

print(keys_view)
# output: dict_keys(['France', 'Japan', 'Chile', 'Canada'])

If you want to have actual Python lists to work with, you should wrap the call to the dict.keys() or dict.values() with the list() function:

keys = list(keys_view)
print(keys)
# output: ['France', 'Japan', 'Chile', 'Canada']

Checking If a Key or Value Is in a Python Dictionary

You can use the in operator in order to check if a key is in a dictionary. This can be used in order to avoid the KeyError that happens when you try to access the value of a key not in the dictionary:

country = 'France'

if country not in countries:
    print(f'Country not found: {country}')
else:
    capital_city = countries[country]
    print(f'The capital of {country} is {capital_city}')

Change the value of the country variable and the message will change, depending on whether the country is a key in the dictionary.

If you want to check for values in the dictionary, you can use the in operator together with the dict.values() method:

print("Paris" in countries.values())
# output: True

print("Berlin" in countries.values())
# output: False

Working with Nested Dictionaries in Python

What Are Nested Dictionaries?

It may sound a bit confusing at first, but you can use dictionaries as values inside another dictionary. This allows for arbitrary nesting of Python dictionaries.

In some situations, nested dictionaries may better represent the structure of real-life data. For example, suppose you have a customers dictionary where every customer ID number  is associated with all the different data that customer has. In Python, it may look like this:

customers = {
    281: {
        'first_name': 'John',
        'last_name': 'Smith',
        'age': 25,
    },
    704: {
        'first_name': 'Mary',
        'last_name': 'Jackson',
        'age': 32,
    },
}

In this structure, customer ID 281 represents John Smith, who is 25 years old.  The dictionary 281 (which contains all John Smith’s data) is contained inside the dictionary customers (along with other dictionaries).

Accessing Data in Nested Dictionaries

Working with nested dictionaries is not any different than working with regular dictionaries. You can simply chain multiple brackets in order to work your way down the dictionary’s levels. For example, if we want to access the last name of customer ID 704, we can do this:

print(customers[704]["last_name"])
# output: Jackson

If it becomes too confusing, you can use intermediary variables for each level in the nested dictionary:

cust_704 = customers[704]  

# Get all of the data for customer ID 704
print(cust_704)
# output: {'first_name': 'Mary', 'last_name': 'Jackson', 'age': 32}

print(cust_704["last_name"])
# output: Jackson

Iterating Over Dictionaries in Python

As with lists and tuples, we can iterate over the elements of a dictionary. Let’s try iterating over the dictionary below:

grades = {'Lucas': 7.2, 'Anna': 9.0, 'Jim': 8.5}

Iterating Over Dictionary Keys

If you simply iterate over the dictionary, you will iterate over its keys:

for name in grades:
    print(name)
# output:
# Lucas
# Anna
# Jim

Iterating Over Dictionary Values

To iterate over values, you can use the dict.values() method:

for grade in grades.values():
    print(grade)
# output:
# 7.2
# 9.0
# 8.5

Iterating Over Dictionary Key-Value Pairs

Finally, you can use the dict.items() method to iterate over each key-value pair. Each pair is returned as a tuple of (key, value):

for pair in grades.items():
    print(pair)
# output:
# ('Lucas', 7.2)
# ('Anna', 9.0)
# ('Jim', 8.5)

You can also unpack each value in its own variable right in the for loop itself:

for name, grade in grades.items():
    print(f'Student {name} got grade {grade}')
# output:
# Student Lucas got grade 7.2
# Student Anna got grade 9.0
# Student Jim got grade 8.5

Iteration Order in Python Dictionaries

Did you notice how the order of iteration was the same one used when we defined the dictionary? This is no coincidence: dictionaries preserve the insertion order of their key-value pairs, and apply that order when we iterate over them. Newly added key-value pairs will always appear last when iterating over a dictionary.

How to Sort a Dictionary in Python

Can We Sort Python Dictionaries?

By themselves, dictionaries do not support the concept of “sorting”. This is due to the dictionary’s intrinsic flexibility

Take a look at the dictionary below.

d = {
    'name': 'John',
    10: False,
    11: 0,
    5.5: [1, 2, 3],
}

Even though it doesn’t really represent anything useful to us, this is still a perfectly valid dictionary in Python. How would we even sort the dictionary if it contains all of these different data types as keys and values?

While Python does have a built-in sorted() function. Here’s what happens when we try to pass this dictionary to it:

for thing in sorted(d):
    print(thing)

TypeError: '<' not supported between instances of 'int' and 'str'

What does the error mean? Since we simply provided the dictionary itself as an argument to sorted(), the dictionary’s keys were taken as the elements to sort. Remember, simply iterating over dictionaries means iterating over their keys.

Since both strings and numbers appear as keys in this dictionary, Python cannot determine whether the strings should be considered “greater” or “less” than the numbers. We’re comparing apples to oranges here, so Python raises the TypeError.

This does not mean that dictionaries are impossible to sort. It just means that we must create a sorting function that precisely defines the sorting logic that we want to apply.

Using a Custom Function to Sort a Python Dictionary

For our example dictionary, the sorting function logic should state whether strings are to be considered “greater than” numbers or not. Then we’ll pass that logic as a parameter to the sorted() function.

Consider the function below that sorts key-value pairs based on the data type of the key (string, integer, etc.). In the function’s logic, strings are considered to be “greater” than floats, and integers are considered to be “greater” than strings:

def sort_by_key_type(pair):
    key = pair[0]  # each pair is a tuple of (key, value)
    if type(key) == float:
        return 0
    elif type(key) == str:
        return 1
    elif type(key) == int:
        return 2

We provide the key-value pairs to the sorted() function using the d.items() method and pass our newly-created sort_by_key_type function as well:

for key, value in sorted(d.items(), key=sort_by_key_type):
    print(key, '->', value)

# output:
# 5.5 -> [1, 2, 3]
# name -> John
# 10 -> False
# 11 -> 0

Note how keys containing floats come first, then strings, then integers – just as desired!

When two keys with the same data type are sorted following this logic, the sorted() function falls back to Python’s “default” sorting logic, which is why the key 10 comes before 11.

You can adapt our sort_by_key_type() function for virtually any sorting logic desired: sort by key, sort by value, sort by data type, etc. You just have to make sure that the logic created allows Python to compare the elements among themselves, whichever they may be.

Want More Python Dictionary Examples?

That’s it for this article! We hope you learned a lot from these Python dictionary examples.

If you still want to learn more about dictionaries in Python, consider checking out our guide on how to use dictionaries. And remember to check out our dedicated platform for learning and practicing all things Python!