What are Python dictionaries?

Python dictionaries are one of the most widely used data structures in Python. They allow us to store and manage data in key-value pairs, offering quick lookups and flexibility when working with complex data.

What is a dictionary?

A Python dictionary is defined by placing key-value pairs inside curly braces {}, separated by commas. Each key is unique and corresponds to a specific value.

Python dictionary
  • Ordered or unordered: Starting from Python 3.7, dictionaries maintain the insertion order of items. Before that, dictionaries were unordered collections. This means that in modern Python versions, the order in which you add items to a dictionary is preserved.

  • Changeable: Python dictionaries are mutable, allowing you to change, add, or remove items after their creation.

  • Duplicates not allowed: Keys must be unique in a dictionary. If you add a duplicate key, it will overwrite the existing key’s value. However, values can be duplicated.

What are Python dictionaries used for?

Dictionaries are extremely useful when you need to store data that can be easily searched and accessed via unique keys. Some common use cases are:

  • Storing user data, such as profiles or settings.

  • Implementing fast lookups for data like configuration files.

  • Counting the frequency of elements in a dataset.

When to use Python dictionaries

We have other data structures such as List, Set in Python. Therefore, it is important to know when to use dictionaries.

  • Python dictionaries are optimized versions of HashMap.

  • HashMaps are developed for faster lookups.

  • Use Python dictionaries when there is a need to search elements faster.

The time complexity to set, get, and delete an item in a dictionary is O(n)O(n).

Dictionary items

Each item in a dictionary is a key-value pair. Keys must be immutable (such as strings, numbers, or tuples), while values can be of any data type.

In the following code, we create a dictionary with mixed data types for values.

# Define a dictionary with various data types
my_dict = {
"name": "John", # A string value representing the person's name
"age": 25, # An integer value representing the person's age
"is_student": True, # A boolean value indicating if the person is a student
"courses": ["Math", "Science"] # A list of courses the person is enrolled in
}
# Print the entire dictionary
print("Dictionary items:", my_dict) # Output the dictionary to see its contents

In this dictionary, the keys are strings ("name", "age", "is_student", "courses") and the values are of mixed types, such as strings, integers, booleans, and lists.

Try adding a course "Chemistry" in the above code and observe the change in the output.

How to create a dictionary

There are multiple ways to create dictionaries in Python. Here are the most common methods.

Method 1: Using curly braces {}

The simplest method to create a dictionary is using curly braces {}.

# Create a dictionary using curly braces
my_dict = {
"name": "Alice", # A string value representing the person's name
"age": 30, # An integer value representing the person's age
"city": "New York" # A string value representing the person's city
}
# Print the created dictionary
print("Created dictionary using curly braces:", my_dict) # Output the dictionary to see its contents

Method 2: Using the dict() function

We can also create a dictionary in Python with the dict() function:

# Create a dictionary using the dict() constructor
my_dict = dict(name="Bob", age=40, city="London") # Create a dictionary with keys and values as parameters
# Print the created dictionary
print("Created dictionary using dict():", my_dict) # Output the dictionary to see its contents

Method 3: Creating an empty dictionary

We can create an empty dictionary and later on add items in it as according to requirements:

# Create an empty dictionary
empty_dict = {} # Initialize an empty dictionary
# Print the empty dictionary
print("Empty dictionary:", empty_dict) # Output the empty dictionary to confirm it's created


Each method creates a dictionary where keys are associated with specific values. You can use either curly braces {} or the dict() function.

How to access dictionary values

Dictionary values can be accessed by using the key inside square brackets or the get() method:

# Accessing dictionary values using key
my_dict = {"name": "Alice", "age": 30}
# Access value using square brackets
print("Name using square brackets:", my_dict["name"])
# Access value using get() method
print("Age using get():", my_dict.get("age"))
# Example of get() returning None if the key does not exist
print("City using get() (non-existing key):", my_dict.get("city"))

We can access values in a dictionary using either square brackets [] or the get() method. The get() method returns None if the key is not found, while using square brackets raises a KeyError.

Try modifying the code to handle the case where the key ("city") doesn't exist by using the get() method with a default value.

Add items to a dictionary

To add a new key-value pair to a dictionary, simply assign a value to a new key.

# Adding items to the dictionary
my_dict = {"name": "Steve", "age": 30}
my_dict["city"] = "Seattle"
# Output the updated dictionary
print("Updated dictionary after adding city:", my_dict)

We add a new key "city" and assign the value "Paris" to it. The dictionary is updated in-place.

Remove dictionary items

You can remove items from a dictionary using several methods, including pop(), del, and clear().

# Removing an item using pop()
my_dict = {"name": "Alice", "age": 30, "city": "Paris"}
removed_item = my_dict.pop("age")
# Output the removed item and updated dictionary
print("Removed item:", removed_item)
print("Updated dictionary after removing 'age':", my_dict)
# Removing an item using del
del my_dict["city"]
print("Updated dictionary after removing 'city':", my_dict)
# Removing all dictionary items with clear()
my_dict_new = {"name": "Alice", "age": 30, "city": "Paris"}
print("New dictionary before clear: ", my_dict_new)
my_dict_new.clear()
print("New dictionary after clear: ", my_dict_new)

In the above code, items are removed from the dictionary using:

  • pop(): Returned the removed value.

  • del: Removed the key-value pair without returning anything.

  • clear(): Removed all elements from the dictionary.

Change dictionary items

You can change the value of an existing key by assigning a new value to that key.

# Changing a value in the dictionary
my_dict = {"name": "Alice", "age": 30}
my_dict["age"] = 35
# Output the updated dictionary
print("Updated dictionary after changing 'age':", my_dict)

We modify the value of the key "age" from 30 to 35 in the dictionary.

Iterate through a dictionary

You can iterate over a dictionary’s keys, values, or both using loops.

my_dict = {"name": "Alice", "age": 30, "city": "Paris"}
# Iterate over keys
for key in my_dict:
print("Key:", key)
# Iterate over values
for value in my_dict.values():
print("Value:", value)
# Iterate over key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")

The items() method allows to iterate over key-value pairs, while the keys() and values() methods iterate over just keys and values, respectively.

Python dictionary methods

Here are some useful methods for working with dictionaries.

my_dict = {"name": "Alice", "age": 30}
# items() method
print("Dictionary items:", my_dict.items())
# keys() method
print("Dictionary keys:", my_dict.keys())
# values() method
print("Dictionary values:", my_dict.values())
# clear() method to empty the dictionary
my_dict.clear()
print("Dictionary after using clear():", my_dict)

Python provides several built-in methods to manipulate dictionaries, including methods to get keys, values, and key-value pairs. The clear() method removes all items from the dictionary.

Challenge

Before we wrap up, let’s put your knowledge of Python dictionaries to a quick challenge!

Count the frequency of elements in a list using a dictionary

Task: Write a function that takes a list as input and returns a dictionary where the keys are the elements of the list, and the values are the frequencies of those elements.

  • Input list

    • input_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']

  • Expected output

    • {‘apple’: 3, ‘banana’: 2, ‘orange’: 1}

def count_frequencies(input_list):
# Write your code here
return None

If you are stuck after you try, you can refer to the given solution by pressing the "Run" button.

Key takeaways

  • Python dictionaries are a powerful and flexible way to store and retrieve data in key-value pairs, offering fast lookups.

  • Dictionaries are mutable, meaning you can add, remove, or modify key-value pairs after creation.

  • Starting from Python 3.7, dictionaries maintain insertion order, meaning that the order in which you add items is preserved.

  • Python dictionaries do not allow duplicate keys, but values can be duplicated.

  • You can access dictionary values using keys or by using methods like get(), which returns None if the key does not exist.

  • Dictionaries are ideal for storing data where quick lookups based on unique keys are required, such as user profiles, settings, or fast element lookups.

Become a Data Analyst with our comprehensive learning path!

Unlock the power of data with our Become a Data Analyst path. Whether you’re a beginner or looking to transition into a data-driven career, this step-by-step journey will equip you with the skills to turn raw data into actionable insights.

From mastering SQL, Python, to learning data visualization and showcasing your analytical skills, this path has it all. Develop expertise in data cleaning, analysis, and storytelling to make informed decisions and drive business success.With hands-on practice, portfolio-building projects, and personalized guidance from our AI mentor, you’ll gain the confidence and knowledge to excel in interviews and secure your first job as a Data Analyst.

Start your data journey today!

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Can Python dictionaries have duplicate keys?

No, Python dictionaries cannot have duplicate keys. If a duplicate key is added, the last value for that key will overwrite the previous one.



my_dict = {'apple': 2, 'apple': 4}
print(my_dict)  # Output: {'apple': 4}

Can dictionary keys be mutable in Python?

No, dictionary keys must be immutable types like strings, numbers, or tuples. Lists and other mutable types cannot be used as dictionary keys.

my_dict = {[1, 2]: 'value'}  # This will raise a TypeError because lists are mutable.

What are dictionary comprehensions in Python?

Dictionary comprehensions provide a concise way to create dictionaries.
They follow the pattern {key: value for item in iterable}.

squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

What are dictionaries also called in Python?

Dictionaries in Python are also referred to as hash maps or hash tables in other programming languages. This is because they store data as key-value pairs and use a hashing function to quickly access values using their keys.


What is the difference between a list and a dictionary in Python?

The key difference between a list and a dictionary in Python is how data is stored and accessed:

  • List: Stores items in an ordered sequence. Items are accessed using their index (position).

my_list[0] retrieves the first item in a list.


  • Dictionary: Stores items as key-value pairs. Items are accessed using keys, which are unique identifiers.

my_dict['key'] retrieves the value associated with 'key'.


Lists are great for ordered collections of data, while dictionaries are better suited for situations where you need to quickly look up values based on a unique key.

Look at List vs. tuple vs. set vs. dictionary in Python for a more detailed discussion.


What are some typical mistakes I might encounter when using dictionaries in Python?

When working with dictionaries, learners often face several common issues:

  • Using mutable types as keys: Remember that dictionary keys must be immutable. Using mutable types like lists or sets will lead to a TypeError. Instead, use immutable types like strings, numbers, or tuples as keys.

  • Duplicate keys: Dictionaries do not allow duplicate keys. If you attempt to add a duplicate key, the existing key’s value will be overwritten without any error, which can lead to data loss if you are not careful.

  • KeyError: If you try to access a key that does not exist in the dictionary, Python will raise a KeyError. To avoid this, use the get() method, which allows you to provide a default value when the key is missing, preventing errors.

  • Mixing up keys and values: Ensure you clearly differentiate between keys and values when accessing data. Use consistent naming conventions and clear documentation to help keep track of what each key represents.

  • Checking key existence: Before accessing a key’s value, it’s good practice to check if the key exists using the in keyword. This can prevent KeyError and ensure your code runs smoothly.


Free Resources