The Dictionary Data Structure in Python

In Python, data structures are fundamental for organizing and managing information efficiently.   Among the various data structures available, dictionaries play a crucial role due to their ability to store data in key-value pairs, allowing for fast and flexible data retrieval. Basically, a dictionary is an unordered, mutable collection that maps unique keys to values, enabling efficient lookups and modifications.

If you’re new to programming and you’re not sure what a key is, don’t worry. A key is simply a unique identifier used to access a specific value within the dictionary. Each key in a dictionary must be unique, immutable (such as a string, number, or tuple), and is used to store and retrieve the corresponding value. Keys provide a way to organize and access data efficiently, allowing you to perform quick lookups, updates, and deletions based on the key.

For example, in the dictionary {“name”: “Alice”, “age”: 30, “city”: “New York”}, the keys are “name”, “age”, and “city”. Each key is associated with a value (“Alice”, 30, and “New York” respectively), and you can access these values by referencing their keys.

Similar to what we did with lists and tuples in previous posts, we’ll learn all about the uses of dictionaries, how to create them, and how to apply basic functions to manage and manipulate them effectively. Let’s get started.

Key Features of Dictionaries

Dictionaries in Python offer several distinct features that make them an essential data structure for many programming tasks. Whereas lists and tuples are very simple, dictionaries need to be a little bit more sophisticated to support their intended uses:

  1. Unordered Collections. Unlike lists and tuples, dictionaries do not maintain any order for the elements. The order of elements can change when the dictionary is modified.

This unordered nature is suitable for scenarios where the order of data does not matter, and only fast retrieval is important.

  1. Mutable. Dictionaries are mutable, meaning you can add, modify, and remove items after the dictionary is created. This flexibility is beneficial for applications requiring dynamic data management, such as updating user profiles or managing inventory systems.
  1. Dynamic Size. Dictionaries can grow and shrink as needed, depending on the data being added or removed. This feature is ideal for situations where the amount of data can vary, such as logging user activities or tracking real-time events.
  1. Unique Keys. Each key in a dictionary must be unique, which prevents duplicate entries and ensures data integrity. This is crucial for applications like databases and indexing systems where each record or entry needs a unique identifier.

These features highlight why dictionaries are a powerful and flexible tool for handling a variety of data management tasks in Python. They should also give you an idea on the potential use cases for this data structure type.

Uses of Dictionaries in Python

Dictionaries are highly versatile and efficient for a variety of tasks, making them useful for a vast array of potential applications. As you go further in your data science journey, you can expect to encounter dictionaries in the following ways:

  1. Mapping Relationships. Dictionaries are excellent for mapping relationships between different pieces of data. This means you can associate a unique key with a specific value.

For instance, storing phone numbers with names as keys will allow for quick lookups of a people’s respective numbers.

  1. Fast Lookups. Dictionaries provide fast lookups, making it easy to retrieve a value associated with a given key quickly, even in large datasets.

An example would be implementing a caching mechanism where previously computed results are stored and quickly retrieved to improve performance.

  1. Data Storage with Key-Value Pairs. Dictionaries store data in key-value pairs, which is a flexible and intuitive way to manage and organize data.

This dictionary feature would be useful in a scenario such as maintaining a record of student grades where student IDs are keys, and grades are values.

  1. Flexible Data Structures. Dictionaries can store various data types as values and even allow nested dictionaries, enabling the creation of complex data structures. A use case would be creating a configuration file structure where different settings are grouped and nested, providing a clear and organized configuration management system.

Now that we have the conceptual part out of the way, let’s proceed to coding dictionaries.

Creating Dictionaries in Python

Creating dictionaries is straightforward, and can be done using various methods. The syntax is somewhat similar to what you’ve learned with lists and tuples, except that you’ll be using curly brackets instead of square ones and parentheses. As alluded to in previous sections, we will not be storing sets of single values in dictionaries. Rather, values will always come paired with keys.

Here are some examples:

Creating an Empty Dictionary

An empty dictionary is created by using a pair of curly braces {}.

# Creating an empty dictionary
empty_dict = {}

Creating a Dictionary with Elements

You can create a dictionary with elements by placing key-value pairs inside curly braces, separated by commas. Keys and values can be of any data type. For example:

  • A dictionary of integers
numbers = {1: "one", 2: "two", 3: "three"}
  • A dictionary of strings.
fruits = {"apple": "red", "banana": "yellow", "cherry": "red"}
  • A mixed dictionary with different data types.
mixed_dict = {"name": "Alice", "age": 30, "is_student": False}

Creating Nested Dictionaries

Dictionaries can also contain other dictionaries as values, allowing you to create complex and nested data structures. For instance:

  • A nested dictionary:
nested_dict = {   "John": {"age": 25, "city": "New York"},   "Anna": {"age": 22, "city": "London"}}

Using the dict() Constructor

Dictionaries can also be created using the dict() constructor, which can accept keyword arguments or a list of tuples.

  • Using keyword arguments:
person = dict(name="John", age=30, city="New York")
  • Using a list of tuples:
items = dict([("apple", 3), ("banana", 5), ("cherry", 7)])

Follow these examples on Jupyter Notebook and see if you can replicate them.

Dictionary Functions and Methods

Dictionaries in Python come with several powerful functions and methods that allow for efficient data manipulation and retrieval. Here are some commonly-used functions and methods that you’ll want to add to your repertoire:

Accessing Values

You can access the value associated with a specific key using square brackets [].

Example:

# Accessing a value
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person["name"])   # Output: Alice

Adding and Modifying Items

You can add a new key-value pair or modify an existing key’s value by assigning it directly.

Example:

# Adding and modifying items
person["age"] = 31  # Modifying an existing key
person["job"] = "Engineer"   # Adding a new key-value pair

Removing Items

Items can be removed from a dictionary using methods like pop(), popitem(), or del.

Example:

# Removing items
person.pop("age")   # Removes the key 'age' and its value
del person["job"]   # Removes the key 'job' and its value

Checking for Existence of Keys

You can check if a key exists in a dictionary using the “in” keyword.

Example:

# Checking for the existence of keys
if "name" in person:
   print("Name exists in the dictionary")

Getting these to work reliably for you takes some practice and experience. As you encounter more use cases, your skills with dictionary functions will incrementally improve.

And there you have it: the dictionary data structure in Python. This is a can’t-miss concept that you’ll need to fully comprehend and apply. As you’ll see in our next lessons, they have a lot of applications that can make your life easier in day to day analytics and machine learning operations.

About Glen Dimaandal

Picture of Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines' most respected SEO agency.
Picture of Glen Dimaandal
Glen Dimaandal is a data scientist from the Philippines. He has a post-graduate degree in Data Science and Business Analytics from the prestigious McCombs School of Business in the University of Texas, Austin. He has nearly 20 years of experience in the field as he worked with major brands from the US, UK, Australia and the Asia-Pacific. Glen is also the CEO of SearchWorks.PH, the Philippines' most respected SEO agency.
ARTICLE & NEWS

Check our latest news

In data science, saving progress is essential. Just like saving your progress in a video game…

In our last lesson, we introduced the concept of Python packages and NumPy in particular. Short…

Now that we have a solid handle on basic Python programming, we can move on to…

Ready to get started?

Reveal the untapped potential of your data. Start your journey towards data-driven decision making with Griffith Data Innovations today.