Python Dictionaries: A Comprehensive Guide

3 min read .

In Python, dictionaries are one of the most powerful and versatile data structures. They allow you to store data in key-value pairs, making them ideal for situations where you need to associate unique keys with values. Whether you’re managing configuration settings, storing user data, or working with JSON, understanding dictionaries is crucial for efficient programming in Python. In this comprehensive guide, we’ll explore the creation, manipulation, and advanced features of Python dictionaries.

What is a Python Dictionary?

A Python dictionary is a mutable, unordered collection of items. Each item in a dictionary is stored as a pair of keys and values. Keys must be unique and immutable, which means they can be strings, numbers, or tuples containing only immutable elements. Values, on the other hand, can be of any data type and can be duplicated.

Creating Dictionaries

You can create a dictionary using curly braces {} with key-value pairs separated by commas, or by using the dict() constructor.

Example 1: Using Curly Braces

# Creating a dictionary with various key-value pairs
person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "is_employee": True
}

Example 2: Using dict()

# Creating a dictionary using the dict() constructor
person = dict(name="Alice", age=30, city="New York", is_employee=True)

Accessing Dictionary Values

You can access values in a dictionary by referring to their keys using square brackets [] or the get() method.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York",
    "is_employee": True
}

# Accessing values using keys
name = person["name"]

# Accessing values using the get() method
age = person.get("age")

# Using get() with a default value if the key is not found
job = person.get("job", "Not Specified")

Modifying Dictionaries

Dictionaries are mutable, so you can change their content by adding, updating, or removing key-value pairs.

Adding or Updating Items

You can add new key-value pairs or update existing ones by assigning values to keys.

person = {
    "name": "Alice",
    "age": 30
}

# Adding a new key-value pair
person["city"] = "New York"

# Updating an existing key-value pair
person["age"] = 31

Removing Items

You can remove items using pop(), popitem(), or del.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Removing a specific item by key
city = person.pop("city")

# Removing and returning the last inserted item
last_item = person.popitem()

# Removing an item by key using del
del person["name"]

Dictionary Operations

Dictionaries support several operations for manipulation and querying.

Keys, Values, and Items

You can retrieve keys, values, and key-value pairs from a dictionary using the keys(), values(), and items() methods.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Retrieving keys
keys = person.keys()

# Retrieving values
values = person.values()

# Retrieving key-value pairs
items = person.items()

Dictionary Comprehensions

Dictionary comprehensions provide a concise way to create dictionaries from iterables.

# Create a dictionary with numbers and their squares
squares = {x: x**2 for x in range(1, 6)}

# Create a dictionary from a list of tuples
pairs = dict([(1, "one"), (2, "two"), (3, "three")])

Nesting Dictionaries

Dictionaries can contain other dictionaries, which is useful for representing more complex data structures.

# A dictionary with nested dictionaries
company = {
    "employee1": {
        "name": "Alice",
        "position": "Engineer"
    },
    "employee2": {
        "name": "Bob",
        "position": "Manager"
    }
}

# Accessing nested dictionary values
engineer_name = company["employee1"]["name"]

Merging Dictionaries

You can merge dictionaries using the update() method or the | operator in Python 3.9 and later.

Using update()

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

# Merging dict2 into dict1
dict1.update(dict2)

Using | Operator (Python 3.9+)

dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}

# Merging dictionaries using |
merged_dict = dict1 | dict2

Querying Dictionaries

You can query dictionaries to check for the existence of keys, retrieve values, and perform conditional operations.

Checking for Key Existence

person = {
    "name": "Alice",
    "age": 30
}

# Check if a key exists
has_city = "city" in person

Iterating Through Dictionaries

You can iterate over dictionaries to process keys, values, or key-value pairs.

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}

# Iterating through keys
for key in person:
    print(key, person[key])

# Iterating through values
for value in person.values():
    print(value)

# Iterating through key-value pairs
for key, value in person.items():
    print(key, value)

Conclusion

Python dictionaries are an essential data structure that offer powerful ways to store and manage data in key-value pairs. From basic creation and modification to advanced operations like merging and querying, dictionaries provide the flexibility needed for a wide range of applications.

Tags:
Python

See Also

chevron-up