Skip to main content

Python Dictionaries

In Python, a dictionary is a versatile and powerful data structure that stores data as key-value pairs. Unlike lists or tuples which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type like strings or numbers.

Introduction to Dictionaries

Think of a Python dictionary like a real-world dictionary: you look up a word (the key) to find its definition (the value). This relationship makes dictionaries extremely useful for storing and retrieving data efficiently.

Dictionaries are:

  • Unordered (prior to Python 3.7, now they maintain insertion order)
  • Mutable (can be changed after creation)
  • Indexed by keys instead of numeric positions

Let's dive into how to create and use dictionaries in Python.

Creating Dictionaries

Basic Dictionary Creation

There are several ways to create a dictionary in Python:

python
# Using curly braces
student = {
"name": "Alice",
"age": 21,
"courses": ["Math", "Computer Science", "Physics"]
}

# Using the dict() constructor
employee = dict(name="John", position="Developer", salary=75000)

# Creating an empty dictionary
empty_dict1 = {}
empty_dict2 = dict()

Accessing Dictionary Values

You can access the values in a dictionary by referring to its key inside square brackets:

python
student = {"name": "Alice", "age": 21, "major": "Computer Science"}

# Accessing values
print(student["name"]) # Output: Alice
print(student["age"]) # Output: 21

Alternatively, you can use the get() method, which has the advantage of not raising an error if the key doesn't exist:

python
print(student.get("name"))      # Output: Alice
print(student.get("address")) # Output: None (doesn't raise an error)
print(student.get("address", "Not Available")) # Output: Not Available (custom default)

Modifying Dictionaries

Dictionaries in Python are mutable, meaning you can change their content after creation.

Adding or Updating Items

python
student = {"name": "Alice", "age": 21}

# Adding a new key-value pair
student["major"] = "Computer Science"

# Updating an existing value
student["age"] = 22

print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science'}

Removing Items

There are several ways to remove items from a dictionary:

python
student = {
"name": "Alice",
"age": 21,
"major": "Computer Science",
"year": "Junior"
}

# Remove a specific item
removed_value = student.pop("year")
print(f"Removed value: {removed_value}") # Output: Removed value: Junior
print(student) # Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science'}

# Remove and return the last inserted item (Python 3.7+)
last_item = student.popitem()
print(f"Last item: {last_item}") # Output: Last item: ('major', 'Computer Science')

# Clear all items
student.clear()
print(student) # Output: {}

Dictionary Methods

Python dictionaries come with several built-in methods that make them even more powerful:

Common Dictionary Methods

python
student = {"name": "Alice", "age": 21, "major": "Computer Science"}

# Get all keys
keys = student.keys()
print(keys) # Output: dict_keys(['name', 'age', 'major'])

# Get all values
values = student.values()
print(values) # Output: dict_values(['Alice', 21, 'Computer Science'])

# Get all key-value pairs as tuples
items = student.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 21), ('major', 'Computer Science')])

# Update dictionary with another dictionary
student.update({"age": 22, "year": "Senior"})
print(student) # Output: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'year': 'Senior'}

Checking if a Key Exists

You can check if a key exists in a dictionary using the in operator:

python
student = {"name": "Alice", "age": 21, "major": "Computer Science"}

print("name" in student) # Output: True
print("address" in student) # Output: False

# To check if a key is NOT in the dictionary
print("address" not in student) # Output: True

Dictionary Comprehensions

Similar to list comprehensions, Python offers dictionary comprehensions for creating dictionaries in a concise way:

python
# Creating a dictionary with squares of numbers
squares = {x: x*x for x in range(6)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Creating a dictionary with specific conditions
even_squares = {x: x*x for x in range(10) if x % 2 == 0}
print(even_squares) # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Nested Dictionaries

Dictionaries can contain other dictionaries, creating nested structures:

python
university = {
"Computer Science": {
"Alice": {"age": 21, "gpa": 3.8},
"Bob": {"age": 20, "gpa": 3.5}
},
"Mathematics": {
"Charlie": {"age": 22, "gpa": 3.9},
"David": {"age": 21, "gpa": 3.7}
}
}

# Accessing nested values
print(university["Computer Science"]["Alice"]["gpa"]) # Output: 3.8

Real-World Applications

Let's explore some practical examples that demonstrate how dictionaries are used in real-world Python applications.

Example 1: Word Frequency Counter

python
def count_word_frequency(text):
# Remove punctuation and convert to lowercase
words = text.lower().replace(".", "").replace(",", "").split()

# Count frequency of each word
frequency = {}
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1

return frequency

sample_text = "Python is amazing. Python is also easy to learn and Python is versatile."
word_count = count_word_frequency(sample_text)
print(word_count)
# Output: {'python': 3, 'is': 3, 'amazing': 1, 'also': 1, 'easy': 1, 'to': 1, 'learn': 1, 'and': 1, 'versatile': 1}

# Finding the most common word
most_common_word = max(word_count, key=word_count.get)
print(f"Most common word: {most_common_word}, Count: {word_count[most_common_word]}")
# Output: Most common word: python, Count: 3

Example 2: Student Records System

python
def create_student_record(name, age, **kwargs):
"""Create a student record with name, age and any additional information."""
student = {"name": name, "age": age}

# Add additional information
for key, value in kwargs.items():
student[key] = value

return student

# Creating student records
alice = create_student_record("Alice", 21, major="Computer Science", gpa=3.8,
clubs=["Programming Club", "Chess Club"])
bob = create_student_record("Bob", 22, major="Physics", research_area="Quantum Mechanics")

# Display student information
print(alice)
# Output: {'name': 'Alice', 'age': 21, 'major': 'Computer Science', 'gpa': 3.8, 'clubs': ['Programming Club', 'Chess Club']}
print(bob)
# Output: {'name': 'Bob', 'age': 22, 'major': 'Physics', 'research_area': 'Quantum Mechanics'}

Example 3: Menu Ordering System

python
# Menu with prices
menu = {
"burger": 5.99,
"pizza": 8.99,
"salad": 4.99,
"soda": 1.99,
"fries": 2.99
}

def calculate_total(order):
"""Calculate the total price of an order."""
total = 0
for item, quantity in order.items():
if item in menu:
total += menu[item] * quantity
else:
print(f"Warning: {item} is not on the menu.")
return total

# Customer's order
order = {"burger": 2, "pizza": 1, "soda": 3, "ice cream": 1}
total = calculate_total(order)
print(f"Order total: ${total:.2f}")
# Output:
# Warning: ice cream is not on the menu.
# Order total: $19.95

Performance Considerations

Python dictionaries are highly optimized for lookups, insertions, and deletions, with most operations having an average time complexity of O(1). This makes them ideal for data that needs to be accessed by a key rather than a position.

When working with large dictionaries, keep these points in mind:

  1. Memory Usage: Dictionaries use more memory than lists for the same number of elements due to their key-value structure.
  2. Key Types: Always use immutable types as dictionary keys (strings, numbers, tuples of immutable objects).
  3. Hash Collisions: In rare cases, hash collisions can slow down dictionary operations.

Summary

Python dictionaries are incredibly versatile data structures that allow you to store data in key-value pairs. They offer:

  • Fast lookup, addition, and deletion of key-value pairs
  • Flexible keys and values that can be of different types
  • Useful built-in methods for common operations
  • Ability to nest other data structures, including other dictionaries

Understanding dictionaries is essential for Python programming as they are used extensively in many Python applications, from simple data storage to complex data processing.

Practice Exercises

  1. Create a dictionary that maps country names to their capitals and add at least five countries.
  2. Write a function that merges two dictionaries and handles duplicate keys appropriately.
  3. Create a program that counts the frequency of each character in a given string using a dictionary.
  4. Implement a simple contact book using nested dictionaries that stores names, phone numbers, and email addresses.
  5. Write a function that inverts a dictionary (makes values the keys and keys the values).

Additional Resources

Now that you understand Python dictionaries, you can effectively use them to organize, store, and manipulate your data in structured and efficient ways!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)