Dictionaries in Python: A Complete Guide

Introduction

Dictionaries in Python are powerful data structures that allow storing and managing data in a key-value format. Unlike lists, which are indexed numerically, dictionaries use unique keys to store and access values efficiently.

In this guide, we will explore Python dictionaries in detail, covering their creation, operations, best practices, exceptions, and practical programs at different levels.


1. What is a Dictionary in Python?

A dictionary in Python is an unordered collection of items where each item is a key-value pair.

Key Features of Dictionaries:

  • Unordered: Items do not have a fixed order.
  • Mutable: You can modify, add, or delete key-value pairs.
  • Unique Keys: Each key in a dictionary must be unique.
  • Efficient Lookup: Accessing values using keys is faster than searching in a list.

Creating a Dictionary

# Empty dictionary
my_dict = {}

# Dictionary with data
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

2. Accessing Dictionary Elements

Using Keys

print(person["name"])  # Output: Alice

Using get() Method

print(person.get("age"))  # Output: 25
  • get() is preferred because it does not raise an error if the key is missing.

Handling Missing Keys

print(person.get("salary", "Key not found"))  # Output: Key not found

3. Modifying Dictionaries

Adding a New Key-Value Pair

person["country"] = "USA"
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

Updating an Existing Key’s Value

person["age"] = 26
print(person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}

Removing Key-Value Pairs

del person["city"]  # Deletes 'city'
age = person.pop("age")  # Removes and returns the value of 'age'
print(person)  # Output: {'name': 'Alice', 'country': 'USA'}

4. Iterating Through Dictionaries

Iterating Over Keys

for key in person:
    print(key)

Iterating Over Values

for value in person.values():
    print(value)

Iterating Over Key-Value Pairs

for key, value in person.items():
    print(f"{key}: {value}")

5. Dictionary Methods and Operations

Common Dictionary Methods

MethodDescription
keys()Returns all dictionary keys
values()Returns all values
items()Returns key-value pairs
update(dict2)Merges dict2 into the current dictionary
clear()Removes all items from the dictionary

Example:

student = {"name": "Bob", "grade": "A"}
print(student.keys())  # Output: dict_keys(['name', 'grade'])

6. Dictionary Comprehensions

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

7. Exception Handling in Dictionaries

1. KeyError (When a non-existent key is accessed)

try:
    print(person["salary"])
except KeyError:
    print("Key not found!")

2. TypeError (When a mutable type like a list is used as a key)

try:
    my_dict = {[1, 2, 3]: "value"}
except TypeError as e:
    print("Error:", e)

8. Practical Programs

Basic Level: Count word frequency in a string

text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)  # Output: {'apple': 3, 'banana': 2, 'orange': 1}

Intermediate Level: Merge two dictionaries and sum common keys

dict1 = {"a": 5, "b": 10, "c": 15}
dict2 = {"b": 20, "c": 25, "d": 30}
merged_dict = {key: dict1.get(key, 0) + dict2.get(key, 0) for key in set(dict1) | set(dict2)}
print(merged_dict)  # Output: {'a': 5, 'b': 30, 'c': 40, 'd': 30}

Advanced Level: Nested dictionary example

employees = {
    "emp1": {"name": "Alice", "age": 30, "department": "HR"},
    "emp2": {"name": "Bob", "age": 25, "department": "Finance"}
}
print(employees["emp1"]["name"])  # Output: Alice

9. Do’s and Don’ts

Do’s:

✔ Use .get() to avoid KeyError.

✔ Use dictionary comprehensions for clean and efficient code.

✔ Use immutable data types (like tuples) as keys.

Don’ts:

✘ Avoid using mutable keys like lists.

✘ Avoid modifying dictionaries while iterating over them.

✘ Avoid using .update() if you need to preserve old values.


Conclusion

Dictionaries in Python are an essential tool for efficient data storage and retrieval. They provide fast lookups, flexible modifications, and various useful methods. By following best practices and understanding potential pitfalls, you can leverage dictionaries effectively in Python programming.

Click here to Download Python

Leave a Comment