← Back to Chapters

Python Dictionaries

? Python Dictionaries

? Quick Overview

A dictionary in Python is a collection of key–value pairs. Each key must be unique and is used to access its corresponding value. Dictionaries are:

  • Unordered – items have no fixed position (in older Python versions).
  • Mutable – you can change, add, or remove items after creation.
  • Dynamic – you can grow or shrink the dictionary at runtime.

⚙️ Key Concepts

  • A dictionary is defined using curly braces {} with key: value pairs.
  • Keys must be immutable types (for example: strings, numbers, tuples).
  • Values can be of any type (strings, numbers, lists, other dictionaries, etc.).
  • Keys are unique – if you repeat a key, the last value assigned will overwrite earlier ones.
  • You access values using the key in square brackets or the get() method.

? Syntax & Structure

Basic syntax to create a dictionary:

? View Dictionary Syntax
# General form
dictionary_name = {
    key1: value1,
    key2: value2,
    key3: value3
}

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

Dictionaries can also be created using the dict() constructor, but using curly braces is the most common and readable approach.

? Code Examples

? Creating a Dictionary

You can create a dictionary using curly braces with key–value pairs.

? View Code Example
person = {"name": "Alice", "age": 25, "city": "New York"}
print(person)
# {'name': 'Alice', 'age': 25, 'city': 'New York'}

? Accessing Values

Access dictionary values using their keys. Use square brackets when you are sure the key exists, or get() when the key might be missing.

? View Code Example
print(person["name"])   # Alice
print(person.get("age"))  # 25

➕ Adding or Updating Items

You can add a new key–value pair or update an existing key simply by assigning to that key.

? View Code Example
person["email"] = "alice@example.com"  # Add new
person["age"] = 26                     # Update existing
print(person)
# {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}

? Removing Items

Remove items using pop(), popitem(), or del.

? View Code Example
person.pop("city")   # Remove by key
person.popitem()     # Remove last inserted item
del person["age"]    # Delete by key
print(person)
# {'name': 'Alice'}

? Live Output & Explanation

? How the Dictionary Changes

Starting with:

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

After adding email and updating age:

person["email"] = "alice@example.com" # Add a new key-value pair
person["age"] = 26 # Update the existing 'age' key
print(person) # Print the updated dictionary

Output:

# Updated dictionary after changes
{'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}

Notice how the value of "age" changed from 25 to 26, and a new key "email" was added. This shows that dictionaries are both mutable and dynamic.

? Use Cases

Use dictionaries when you need:

  • Fast lookups by a meaningful key (like username, roll number, or product ID).
  • To group related data together (like a record of a person, product, or configuration).
  • To count or map items (for example, word counts, frequency tables).

? Tips & Best Practices

  • Use get() to safely access keys that might not exist, e.g. person.get("phone").
  • Remember that dictionaries are mutable, so changes affect the original object.
  • Keep your keys simple and consistent, usually strings like "name", "age", etc.
  • Avoid using duplicate keys – the last value for a key will overwrite earlier ones.
  • Do not use mutable types (like lists) as keys; only immutable types are allowed.
  • Handle missing keys properly to avoid KeyError (use get() or in checks).

? Try It Yourself

  • Create a dictionary of your favorite movies and their release years.
  • Update one of the movies with a new release year.
  • Access a value safely using get() for a key that might not exist.
  • Remove a movie from the dictionary using pop() and print the updated dictionary.