Skip to Content
Course content

A dictionary in Python is an unordered, mutable, and indexed collection of key-value pairs. Each key in a dictionary is unique and maps to a corresponding value. Dictionaries are widely used in Python to store data in a way that allows for fast retrieval of values based on the key.

1. Creating Dictionaries

A dictionary is created using curly braces {} or the dict() function. Keys and values are separated by a colon : within the dictionary.

Example 1: Creating a dictionary using curly braces

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

Example 2: Creating a dictionary using dict() function

person = dict(name="Alice", age=25, city="New York")

2. Accessing Elements in a Dictionary

You can access dictionary values by referring to their key using square brackets []. Alternatively, the get() method can be used, which allows for safer retrieval of values.

Example 1: Accessing a value using the key

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

Example 2: Accessing a value using the get() method

print(person.get("age"))  # Output: 25

The get() method returns None if the key is not found, which avoids raising a KeyError.

3. Modifying and Adding Elements

Dictionaries are mutable, so you can change or add new key-value pairs.

Example 1: Modifying a value

person["age"] = 26  # Modifying the age

Example 2: Adding a new key-value pair

person["email"] = "alice@example.com"  # Adding new key-value pair

4. Removing Elements

You can remove elements from a dictionary using various methods, such as del, pop(), and popitem().

Example 1: Removing an element using del

del person["email"]  # Removes the key 'email' and its value

Example 2: Removing an element using pop()

age = person.pop("age")  # Removes 'age' and returns its value
print(age)  # Output: 26

Example 3: Removing the last item using popitem()

item = person.popitem()  # Removes and returns the last key-value pair
print(item)

5. Dictionary Methods

Python dictionaries come with several useful methods to manipulate and retrieve data:

  • keys(): Returns a view of all the keys in the dictionary.
  • values(): Returns a view of all the values in the dictionary.
  • items(): Returns a view of all key-value pairs as tuples.
  • update(): Updates a dictionary with the key-value pairs from another dictionary or iterable.

Example of dictionary methods:

# Keys of the dictionary
print(person.keys())  # Output: dict_keys(['name', 'city'])

# Values of the dictionary
print(person.values())  # Output: dict_values(['Alice', 'New York'])

# Items of the dictionary
print(person.items())  # Output: dict_items([('name', 'Alice'), ('city', 'New York')])

# Updating the dictionary with new key-value pairs
person.update({"gender": "Female", "job": "Engineer"})

6. Nesting Dictionaries

Dictionaries can also store other dictionaries as values, enabling complex hierarchical structures.

Example of a nested dictionary:

people = {
    "person1": {"name": "Alice", "age": 25, "city": "New York"},
    "person2": {"name": "Bob", "age": 30, "city": "Los Angeles"}
}

# Accessing values inside nested dictionaries
print(people["person1"]["name"])  # Output: Alice

7. Iterating Through Dictionaries

You can loop through a dictionary to access keys, values, or both.

Example 1: Iterating through keys

for key in person:
    print(key)  # Prints each key in the dictionary

Example 2: Iterating through values

for value in person.values():
    print(value)  # Prints each value in the dictionary

Example 3: Iterating through key-value pairs

for key, value in person.items():
    print(f"{key}: {value}")  # Prints each key and its corresponding value

8. Dictionary Comprehension

Dictionary comprehension provides a concise way to create dictionaries. It follows a similar syntax to list comprehensions but works with key-value pairs.

Example of dictionary comprehension:

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

9. Dictionary Use Cases

Dictionaries are highly versatile and are commonly used in Python for:

  • Storing configuration settings: Storing settings or parameters in key-value pairs for easy lookup.
  • Representing records: Representing data with fields, such as database records, using keys as field names and values as field data.
  • Counting occurrences: Using keys as items and values as their count in problems like word frequency analysis or item counting.

Example: Counting word frequency

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

Summary of Dictionaries in Python

  • Dictionaries are mutable, unordered collections that store data as key-value pairs.
  • They support various methods like get(), keys(), values(), items(), and more for accessing and manipulating data.
  • Dictionaries can be nested, allowing them to represent more complex data structures.
  • Common use cases include storing configurations, counting items, and representing data records.

Dictionaries are an essential data structure in Python and are widely used due to their flexibility and efficient access patterns based on keys.

Commenting is not enabled on this course.