Python Dictionaries

Python dictionaries are versatile and powerful data structures used to store data in key-value pairs. They are particularly useful due to their efficiency and flexibility. In this tutorial, we’ll dive deeply into Python dictionaries, covering everything from the basics to advanced usage.

1. What is a Dictionary?

A dictionary in Python is a collection that stores values indexed by keys. Keys must be unique and immutable (e.g., strings, numbers, tuples). Values, however, can be of any type and duplicated.

Here’s an example of a simple dictionary:

student = {
    'name': 'John Doe',
    'age': 23,
    'major': 'Computer Science'
}

2. Creating Dictionaries

You can create dictionaries using different methods:

Method 1: Literal syntax
my_dict = {
    'name': 'Alice',
    'city': 'New York',
    'age': 25
}

Method 2: Using the dict() constructor
my_dict = dict(name='Alice', city='New York', age=25)

Method 3: From a list of tuples
my_dict = dict([('name', 'Alice'), ('city', 'New York'), ('age', 25)])

3. Accessing Dictionary Values

Values in a dictionary can be accessed using their corresponding keys:

person = {'name': 'Bob', 'age': 30}
print(person['name'])  # Output: Bob

If you try to access a key that doesn’t exist, Python raises a KeyError. To avoid this, use .get():

print(person.get('city'))  # Output: None
print(person.get('city', 'Unknown'))  # Output: Unknown

4. Modifying Dictionaries

Dictionaries are mutable. You can easily add, change, or remove key-value pairs.

Adding or updating a value
student = {'name': 'Charlie', 'age': 21}
student['major'] = 'Physics'  # Adding new key-value pair
student['age'] = 22           # Updating existing key-value pair

Removing items

Use del, .pop(), or .popitem():

student = {'name': 'Charlie', 'age': 21, 'major': 'Physics'}

del student['age']  # removes the 'age' key
major = student.pop('major')  # removes and returns the value
key, value = student.popitem()  # removes and returns a random key-value pair

Clearing all items
student.clear()  # Empties the dictionary

5. Dictionary Methods

Python dictionaries come with several built-in methods:

MethodDescription
.keys()Returns a view of dictionary’s keys
.values()Returns a view of dictionary’s values
.items()Returns a view of dictionary’s key-value pairs
.update()Adds or updates key-value pairs from another dictionary
.setdefault()Gets the value of a key or sets it if not present
.copy()Returns a shallow copy of the dictionary

Example:

student = {'name': 'David', 'age': 25}

print(student.keys())    # Output: dict_keys(['name', 'age'])
print(student.values())  # Output: dict_values(['David', 25])
print(student.items())   # Output: dict_items([('name', 'David'), ('age', 25)])

6. Iterating Over Dictionaries

Use loops to iterate over dictionary keys, values, or both:

Iterating over keys:
for key in student:
    print(key, student[key])

Iterating over values:
for value in student.values():
    print(value)

Iterating over keys and values:
for key, value in student.items():
    print(f'{key}: {value}')

7. Nested Dictionaries

A dictionary can store another dictionary as a value:

students = {
    'Alice': {'age': 24, 'major': 'Math'},
    'Bob': {'age': 22, 'major': 'Physics'}
}

print(students['Alice']['major'])  # Output: Math

8. Dictionary Comprehensions

Dictionary comprehensions allow you to create dictionaries using concise, readable syntax:

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

You can add conditions as well:

even_squares = {num: num**2 for num in range(1, 10) if num % 2 == 0}
print(even_squares)
# Output: {2: 4, 4: 16, 6: 36, 8: 64}

Common Use Cases

Python dictionaries are commonly used for:

  • Representing real-world data (e.g., JSON, databases)
  • Counting occurrences (frequency tables)
  • Implementing simple databases or configuration settings
  • Efficient lookups and indexing

Example of counting occurrences:

words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = {}

for word in words:
    word_counts[word] = word_counts.get(word, 0) + 1

print(word_counts)
# Output: {'apple': 3, 'banana': 2, 'orange': 1}

Summary and Best Practices

Key points:
  • Dictionaries store key-value pairs.
  • Keys must be immutable; values can be mutable.
  • Use .get() method to safely retrieve values.
  • Dictionary comprehensions simplify dictionary creation.
  • Nested dictionaries help represent complex structures.
Best practices:
  • Choose meaningful key names for clarity.
  • Always check for keys’ existence before accessing them directly.
  • Use built-in methods effectively to write efficient and readable code.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top